响应生命周期事件在组件安装后停止



我已经使用create-react-app命令创建了入门项目。 并添加了两个生命周期事件,componentDidMount(( 工作正常,但 componentWillReceiveProps(( props 不触发。

索引.js:

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

应用.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"
}
}

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

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

如果您添加一个计数器和一个按钮来增加状态道具,您将看到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只会在您主动卸载组件时触发 - 这在您的示例中永远不会发生。如果您添加 即路由或某些将在某个时候卸载的组件,您也可以触发此函数。

有关更多详细信息,请查看文档。

我认为你应该再读一个 React 组件的生命周期。

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

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

希望对您有所帮助^^

最新更新