react中警告提示:
react_devtools_backend.js:4061 Warning: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the Home component.

代码:
class App extends React.Component{
constructor(props) {
super(props);
...
this.state = {
name:"开发测试",
adopters:[]
}
this.init()
}
init(){
...
this.setState({adopters:result})
}
因为在constructor() 中初始化state使用了setState,调整如下即可:
class App extends React.Component{
constructor(props) {
super(props);
...
this.state = {
name:"开发测试",
adopters:[]
}
}
componentDidMount(){
this.init()
}
init(){
...
this.setState({adopters:result})
}
在React应用中遇到一个警告:Can't call setState on a component that is not yet mounted.该警告提示在构造函数中不应当使用setState。正确做法是在componentDidMount生命周期方法中初始化数据。修正后的代码将init方法调用移至componentDidMount,避免了在组件未挂载时尝试更新状态。
2万+

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



