React setState 只能更新一个已挂载或挂载的组件

新手上路,请多包涵

我收到以下警告

“警告:setState(…):只能更新已安装或正在安装的组件。这通常意味着您在未安装的组件上调用了 setState()。这是一个空操作。请检查 ContactPage 组件的代码。”

当我第一次访问联系页面时,一切正常。然后,如果我离开页面并返回,则会引发警告。

联系页面组件:

 import React, { Component, PropTypes } from 'react';
import AppStore from '../../stores/AppStore';
import AppActions from '../../actions/AppActions';
import DataContent from './DataContent';

const title = 'Contact Us';

class ContactPage extends Component {

    constructor(props) {
        super(props);
        this.state = AppStore.getState();
        AppActions.getData();
    }

  static contextTypes = {
    onSetTitle: PropTypes.func.isRequired,
  };

  componentWillMount() {
    this.context.onSetTitle(title);
    AppStore.listen(this.onChange.bind(this));
}

componentWillUnmount() {
    AppStore.unlisten(this.onChange.bind(this));
}

onChange(state) {
    this.setState(state);
}

renderData() {
    return this.state.data.map((data) => {
        return (
            <DataContent key={data.id} data={data} />
        )
    })
}

  render() {
    return (
      <div className={s.root}>
        <div className={s.container}>
          <h1>{title}</h1>
          <div>
              { this.renderData() }
          </div>
        </div>
      </div>
    );
}

}

export default ContactPage;

当我放入调试器时,在加载联系页面时它会触发 componentWillMount()。当我离开联系页面时,它会触发 componentWillUnmount()。当我导航回页面时,它再次点击 componentWillMount() ,然后在点击 onChange(state) 函数时抛出错误。

原文由 erichardson30 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 516
2 个回答

问题是前一个组件实例的侦听器仍然被注册。并且由于不再安装先前的实例,您会收到该错误。

.bind 总是返回一个 函数。所以如果你这样做

AppStore.unlisten(this.onChange.bind(this));

那么您正在尝试删除一个不存在的侦听器(当然会失败)。它 不会 删除您注册的侦听器 AppStore.listen(this.onChange.bind(this))


要解决这个问题,您应该在构造函数中绑定 一次 处理程序:

 this.onChange = this.onChange.bind(this);

然后使用 AppStore.listen(this.onChange)AppStore.unlisten(this.onChange)

原文由 Felix Kling 发布,翻译遵循 CC BY-SA 3.0 许可协议

在更改之前,状态检查组件已安装。

 render() {
   return (
     <div ref="root" className={s.root}>
       // ----
     </div>
   )};

 onChange(state) {
   if(this.refs.root) {
     this.setState(state);
   }
 }

我认为这会对你有所帮助。

原文由 Janaka Pushpakumara 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题