在lifeDidMount之后,生命周期事件会停止

时间:2017-07-11 11:25:08

标签: reactjs

我用create-react-app命令创建了启动项目。并添加了两个生命周期事件,componentDidMount()工作正常但componentWillReceiveProps()不会触发。

index.js:

ReactDOM.render(
  <App appState={appState} />,
  document.getElementById('root')
);

App.js:

class App extends Component {
  render() {
    return (
      <div className="App">
        <EasyABC appState={this.props.appState} />
      </div>
    )
  }
}

export default App;

EasyABC.jsx文件:

     @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:

{
  "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"
  }
}

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

2 个答案:

答案 0 :(得分:5)

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

如果你添加一个计数器和一个按钮来增加状态道具,你会看到componentWillReceiveProps功能火:

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只会在您主动卸载组件时触发 - 这在您的示例中永远不会发生。如果您添加ie路由或某些将在某个时候卸载的组件,您也可以触发此功能。

有关详细信息,请查看docs

答案 1 :(得分:2)

我想你应该多读一遍Lifecycle Of React Component

如果组件运行,将调用

函数componentDidMount

如果更新道具,将调用

函数componentWillReceiveProps:)

希望它对你有帮助^^