【问题标题】:What does "Warning: setState(...): Can only update a mounted or mounting component" mean?“警告:setState(...):只能更新已安装或已安装的组件”是什么意思?
【发布时间】:2017-01-19 08:07:58
【问题描述】:

编辑

“Warning: setState(...): Can only update amounted ormounting component”是什么意思?

【问题讨论】:

  • 你应该放回与答案对应的相关代码

标签: javascript html reactjs react-router react-jsx


【解决方案1】:

首先,像这样将所有 React 组件重命名为 Camel Case。

class firstChild ... --> class FristChild
<fristChild> --> <FristChild>

其次,在您的FirstChild 渲染方法中,您应该将您的元素包装到一个封闭标签中,如下所示:

class FirstChild extends Component {
render(){
   return (
      <div>
        <input ... />
        <button ... />
      </div>
   )
}
}

第三,当你在this.props.children 上使用cloneElement 时,你应该在secondChildren 中使用Proptypes.&lt;type&gt; 而不是Propstypes.&lt;type&gt;.isRequired。查看here 了解原因。

class SecondChild extends Component {
    static propTypes = {
      submitSuccess: React.PropTypes.bool, // remove isRequired
    }
}

无论如何,我已经测试了你的代码,它工作正常。

【讨论】:

    【解决方案2】:

    您可以尝试使用componentWillUnmount生命周期函数来检查组件何时被卸载。

    您还可以在设置状态之前使用标志来表示组件已卸载:

    saveName(nameText) {
        if (!this.isUnmounted){
            this.setState({submitSuccess: true});
        }
    }
    
    componentWillUnmount() {
        this.isUnmounted = true;
    }
    

    【讨论】:

    • 抱歉,您能解释一下为什么我应该按照您的建议做吗?努力学习。为什么要在设置状态之前卸载组件?
    • 我的猜测是其中一个事件发生在组件安装之前。可能是 FirstChild 上的 changeName。
    猜你喜欢
    • 2017-04-26
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 2019-08-15
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    相关资源
    最近更新 更多