this.setState 不更新状态 [英] this.setState does not update state

查看:57
本文介绍了this.setState 不更新状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 handleFormSubmit 中使用 this.setState 但是 this.setState 没有更新,我不知道为什么.如果我在 this.setState 之前运行 console.log(updatePosition) 我可以知道所有数据都在那里.我错过了什么?我对 handleChange 使用了类似的代码,我没有问题.

I'm trying to use this.setState within handleFormSubmit however this.setState isn't updating and I'm not sure why. If I run console.log(updatePosition) before this.setState I can that all the data is there. What am I missing? I use similar code for handleChange and I don't have problems.

constructor(props) {
  super(props);

  let uniqueId = moment().valueOf();

  this.state = {
    careerHistoryPositions: [{company: '', uniqueId: uniqueId, errors: {} }],
  };

  this.handleFormSubmit = this.handleFormSubmit.bind(this);
}




handleFormSubmit(event) {
  event.preventDefault();
  const { careerHistoryPositions } = this.state;

  const updatePosition = this.state.careerHistoryPositions.map((careerHistoryPosition) => {
    const errors = careerHistoryValidation(careerHistoryPosition);
    return { ...careerHistoryPosition, errors: errors  };
  });

  console.log(updatePosition)
  this.setState({ careerHistoryPositions: updatePosition });
}

推荐答案

请记住,状态不会立即更新.如果要检查它是否已更新,请使用回调函数.内容如下:

Keep in mind that the state isn't updated immediately. If you want to check if it's updated use callback function. Something as follows:

this.setState({ careerHistoryPositions: updatePosition }, () => console.log(this.state.careerHistoryPositions);

来自文档:

setState() 不会立即改变 this.state 而是创建一个待处理的状态转换.调用 this 后访问 this.state方法可能会返回现有值.没有保证调用 setState 和调用的同步操作可能进行批处理以提高性能.

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

希望这会有所帮助.

这篇关于this.setState 不更新状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆