我已经使用create-react-app命令创建了starter项目。并添加了两个生命周期事件,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"
}
}我在网上搜索,但找不到任何解决方案。
发布于 2017-07-11 19:34:30
我觉得你应该多读一篇Lifecycle Of React Component。
如果组件运行,将调用函数componentDidMount。
如果更新了Props,将调用函数componentWillReceiveProps :)
希望对您有帮助^^
发布于 2017-07-11 19:33:42
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才会触发-这在您的示例中永远不会发生。如果你添加了在某个时刻卸载的路由或一些组件,你也可以触发这个函数。
有关更多详细信息,请查看docs。
https://stackoverflow.com/questions/45033217
复制相似问题