首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >react生命周期事件在componentDidMount之后停止

react生命周期事件在componentDidMount之后停止
EN

Stack Overflow用户
提问于 2017-07-11 19:25:08
回答 2查看 378关注 0票数 1

我已经使用create-react-app命令创建了starter项目。并添加了两个生命周期事件,componentDidMount()运行良好,但componentWillReceiveProps()道具无法触发。

index.js:

代码语言:javascript
复制
ReactDOM.render(
  <App appState={appState} />,
  document.getElementById('root')
);

App.js:

代码语言:javascript
复制
class App extends Component {
  render() {
    return (
      <div className="App">
        <EasyABC appState={this.props.appState} />
      </div>
    )
  }
}

export default App;

EasyABC.jsx文件:

代码语言:javascript
复制
     @observer
export default class EasyABC extends Component{
    constructor(props){
        super(props)
    }
    componentDidMount(){
        this.props.appState.index=0
        let letterSound = document.querySelector("audio[data-key='letter']")
        letterSound.play()
    }
    componentWillReceiveProps(){//never stops here
        debugger
    }...

如果需要,package.json:

代码语言:javascript
复制
{
  "name": "assasment1",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "classnames": "^2.2.5",
    "mobx": "^3.2.0",
    "mobx-react": "^4.2.2",
    "react": "^15.6.1",
    "react-dom": "^15.6.1"
  },
  "devDependencies": {
    "custom-react-scripts": "0.0.23"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

我在网上搜索,但找不到任何解决方案。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-07-11 19:34:30

我觉得你应该多读一篇Lifecycle Of React Component

如果组件运行,将调用函数componentDidMount

如果更新了Props,将调用函数componentWillReceiveProps :)

希望对您有帮助^^

票数 2
EN

Stack Overflow用户

发布于 2017-07-11 19:33:42

componentWillReceiveProps只会在随后的渲染中触发,而不是第一次。据我所知,您没有在应用程序中更新任何道具或状态。

如果您添加一个计数器和一个按钮来增加状态属性,您将看到componentWillReceiveProps函数触发:

代码语言:javascript
复制
class App extends Component {
  constructor() {
    super();
    this.state = { count: 0 };

    this.onClick = this.onClick.bind(this);
  }
  componentWillReceiveProps() {
    debugger; // <-- will now fire on every click
  }
  onClick() { 
    this.setState({ count: this.state.count + 1 });
  }
  render() {
    return (
      <button onClick={this.onClick}>Clicked {this.state.count} times</button>
    );
  }
}

只有当您主动卸载组件时,componentWillUnmount才会触发-这在您的示例中永远不会发生。如果你添加了在某个时刻卸载的路由或一些组件,你也可以触发这个函数。

有关更多详细信息,请查看docs

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45033217

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档