-
控制台出现警告:
Warning: Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component -
原因:
React生命周期的componentWillMount和componentDidMount中的setState使用错误。
-
componentWillMount
在render()方法之前执行,该方法中使用setState不会发生重新渲染。 -
componentDidMount
在render()方法之后立即执行,该方法中使用setState会触发重新进行渲染。re
- 解决办法:
setState只能用在componentDidMount中,而不是componentWillMount
本文解析了React中控制台警告“Can only update a mounted or mounting component”的原因,通常是因为在componentWillMount和componentDidMount中错误地使用了setState。componentWillMount中使用setState不会触发重新渲染,而componentDidMount中使用则会触发。解决方法是在componentDidMount中使用setState。

3449

被折叠的 条评论
为什么被折叠?



