我用create-react-app命令创建了启动项目.并添加了两个生命周期事件,componentDidMount()工作正常但componentWillReceiveProps()不会触发.
index.js:
ReactDOM.render(
<App appState={appState} />,
document.getElementById('root')
);
Run Code Online (Sandbox Code Playgroud)
App.js:
class App extends Component {
render() {
return (
<div className="App">
<EasyABC appState={this.props.appState} />
</div>
)
}
}
export default App;
Run Code Online (Sandbox Code Playgroud)
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
}...
Run Code Online (Sandbox Code Playgroud)
如果需要的话; 的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"
}
}
Run Code Online (Sandbox Code Playgroud)
我在网上搜索但无法找到任何解决方案..
componentWillReceiveProps只会在后续渲染时触发,而不是第一次渲染.据我所知,您没有在应用程序中更新任何道具或状态.
如果你添加一个计数器和一个按钮来增加状态道具,你会看到componentWillReceiveProps函数fire:
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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
componentWillUnmount只有在您主动卸载组件时才会触发 - 这在您的示例中永远不会发生.如果添加ie路由或某些将在某个时候卸载的组件,您也可以触发此功能.
有关更多详细信息,请查看文档.
| 归档时间: |
|
| 查看次数: |
314 次 |
| 最近记录: |