React setState只能更新已安装或安装的组件

eri*_*n30 22 javascript reactjs

我收到以下警告

"警告: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;
Run Code Online (Sandbox Code Playgroud)

当我把调试器放入,在加载联系页面时它会命中componentWillMount().当我离开联系页面时,它会命中componentWillUnmount().当我导航回页面时,它会再次命中componentWillMount(),然后在遇到onChange(state)函数时抛出错误.

Fel*_*ing 38

问题是前一个组件实例的监听器仍然是已注册的.并且因为先前的实例不再安装,所以您会收到该错误.

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

AppStore.unlisten(this.onChange.bind(this));
Run Code Online (Sandbox Code Playgroud)

那么你试图删除一个不存在的监听器(当然失败了).它并不会删除您注册的监听器AppStore.listen(this.onChange.bind(this))


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

this.onChange = this.onChange.bind(this);
Run Code Online (Sandbox Code Playgroud)

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


Jan*_*ara 6

在更改之前,将安装状态检查组件.

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

 onChange(state) {
   if(this.refs.root) {
     this.setState(state);
   }
 }
Run Code Online (Sandbox Code Playgroud)

我想这会对你有所帮助.