【问题标题】:State not updating until 2nd time the form is submitted状态直到第二次提交表单才更新
【发布时间】:2019-08-28 12:45:31
【问题描述】:

因此,当添加会话并提交表单时,我希望将客户的价格转移到我的会话状态中。这就是我在这部分代码中尝试做的事情。

state = {
    id: null, 
    name: null, 
    duration: null, 
    dayOfWeek: null,
    price: null
  }

handleSubmit = (e) => {
    e.preventDefault();
    let newPrice = 0;
    this.props.clientList.filter(client => {
      if (client.name === this.state.name) 
      {newPrice = client.price}
      this.setState({
        price : newPrice
      });
      console.log("price = " + this.state.price, 'newPrice = ' + newPrice)
    })
    this.props.addSession(this.state);
    e.target.reset();
    this.setState({
      id: null, 
      name: null, 
      duration: null, 
      dayOfWeek : null
    });
  }   

发生了什么,我试图在控制台的图像中描绘,我添加的两个会话是,当我第一次添加它时,它会注销 price = null 和 newPrice = 40 ,第二次是 price = 40. 为什么我的代码在这里不起作用?

如果需要,我可以添加更多代码。让我知道你需要看什么,谢谢!

【问题讨论】:

  • 我也刚刚意识到,在我将状态设置回 null 的代码的最后一部分中,我没有 price: null。当我添加它时,它甚至不能像以前那样第二次工作。

标签: javascript reactjs redux state


【解决方案1】:

setState 是一个异步函数...并且您正在通过在setState 之后直接调用以下行来访问您的 old-state-value:

this.props.addSession(this.state); 

-

handleSubmit = (e) => {
  e.preventDefault();
  let newPrice = 0;
  this.props.clientList.filter((client) => {
    if (client.name === this.state.name) {
      newPrice = client.price;
    }

    this.setState({
      price: newPrice,
    });
    console.log(`price = ${this.state.price}`, `newPrice = ${newPrice}`);
  });

  this.props.addSession({ ...this.state, price: newPrice }); // <- Look at this
  e.target.reset();
  this.setState({
    id: null,
    name: null,
    duration: null,
    dayOfWeek: null,
  });
};

【讨论】:

    【解决方案2】:

    状态不会立即更新。如果您在状态更新后需要回调您可以使用

    this.setState({
          price : newPrice
    }, ()=>{
     //CallBack here
           console.log("price = " + this.state.price, 'newPrice = ' + newPrice)
    })
    

    希望对您有所帮助。如果我不明白你的问题。请回复

    【讨论】:

    • 有没有办法让状态及时更新,这样当我提交表单时,数据就可以输出了?
    • 我认为我不一定需要回调。我只需要它能够按时将数据发送给我的动作创建者
    • @josephT setState 非常快。用户不会看到状态变化的区别,可以使用回调。当您提交表单时,数据将准备好根据需要输出。
    • @josephT 如果您需要发送 newPrice 到您的操作中。您只能将 newPrice 值发送给您的操作创建者。由于setState 是async,所以状态不会立即更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 2014-03-22
    • 2022-01-16
    • 2012-09-12
    相关资源
    最近更新 更多