【问题标题】:setState(…): Can only update a mounted or mounting componentsetState(…):只能更新一个挂载或挂载的组件
【发布时间】:2016-07-10 06:56:52
【问题描述】:

这是代码。不知道为什么会出现问题。

class TeacherForm extends Component {
  constructor({ data }) {
    super();

    this.isUpdatingForm = !! data;
    this.state = Object.assign({ ... });

    this.handleSubmit = this.handleSubmit.bind(this);
    this.removeTeacher = this.removeTeacher.bind(this);
  }

  handleChange(value, field) {
    this.setState({ shouldUpdate: true, [field]: value });
  }

  handleSubmit(e) {
    e.preventDefault();
    const { name, subjects, parttime, timing } = this.state;

    if (this.isUpdatingForm) {
      return update.call({
        _id: this.props.data._id,
        transaction: { name, subjects, parttime, timing },
      }, () => this.setState({ shouldUpdate: false }));
    }

    return add.call();
  }

  removeTeacher() {
    return remove.call(this.props.data._id);
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
         ...
      </form>
    );
  }
}

update.call 回调中的 handleSubmit 方法抛出错误。这通常会在我调用 removeTeacher 并且列表更新并且该组件卸载时出现。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    听起来回调() =&gt; this.setState({ shouldUpdate: false }) 是在组件卸载后执行的。那可能吗?如果是这样,解决此问题的一种方法是将这部分替换为

    return update.call({
      _id: this.props.data._id,
      transaction: { name, subjects, parttime, timing },
    }, () => { !this.unmounted && this.setState({ shouldUpdate: false }); });
    

    添加

    componentWillUnmount() {
      this.unmounted = true;
    }
    

    【讨论】:

    • 它应该在表单提交时运行。是否有任何理由说明它在卸载后可能会运行。如果它被卸载,表单永远不会被提交,所以技术上不应该运行。
    • 组件挂载时同步调用Update.call。但看起来改变状态的回调可以在组件卸载后触发
    • 您可以在 1)在 update.call 之前处理提交,2)在回调中 3)在 componentWillUnmount 中添加日志,并查看它们被调用的顺序
    猜你喜欢
    • 2016-05-22
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多