避免在componentWillMount()
中使用进行setState
操作.
componentWillMount()
在组件将要挂载时被立即调用. 这个调用发生在render()
函数执行之前, 所以如果在componentWillMount
里面设置了state, 这个设置的state是不会触发重新渲染的.
同样我们也需要注意不要在componentWillMount()
中引入其他可能会导致问题的代码.
如果你有类似的需求, 请在componentDidMount
里面完成.
function componentDidMount() {
axios.get(`api/messages`)
.then((result) => {
const messages = result.data
console.log("COMPONENT WILL Mount messages : ", messages);
this.setState({
messages: [...messages.content]
})
})
}
看完两件小事
如果你觉得这篇文章对你挺有启发,我想请你帮我两个小忙:
- 把这篇文章分享给你的朋友 / 交流群,让更多的人看到,一起进步,一起成长!
- 关注公众号 「IT平头哥联盟」,公众号后台回复「资源」 免费领取我精心整理的前端进阶资源教程