【问题标题】:Not setting state with data get back from fetch call不使用从 fetch 调用返回的数据设置状态
【发布时间】:2020-03-01 18:27:47
【问题描述】:

我可以在setState行前后console.log(data),但没有成功设置confirmationDetail的状态,但是购物车可以工作。

    const init = {
      method: 'POST',
      body: JSON.stringify(information),
      headers: { 'Content-Type': 'application/json' }
    };
    fetch('api/orders', init)
      .then(response => response.json())
      .then(data => {
        if (!data.error) {
          this.setState(state => ({ cart: [], confirmationDetail: data }));
        } else {
          Swal.fire(data.error);
        }
      });
  }```

【问题讨论】:

  • 你能分享你的状态对象吗
  • this.state = { cart: [], confirmationDetail: {} }

标签: javascript reactjs api fetch


【解决方案1】:

我猜在 fetch 调用中使用 this 是有问题的。在您尝试调用它时,它实际上是未定义的。 可以试试吗?

    const init = {
      method: 'POST',
      body: JSON.stringify(information),
      headers: { 'Content-Type': 'application/json' }
    };
    const that = this;
    fetch('api/orders', init)
      .then(response => response.json())
      .then(data => {
        if (!data.error) {
          that.setState(state => ({ cart: [], confirmationDetail: data }));
        } else {
          Swal.fire(data.error);
        }
      });

【讨论】:

  • 同样的问题
【解决方案2】:

试试这个:

          fetch('api/orders', init)
            .then((response) => response.json())
            .then((findresponse) =>{
                this.setState({
                   cart: [], 
                   confirmationDetail: data
                });
            })
            .catch((err) =>{
                console.log(err);
                }
            });

【讨论】:

    【解决方案3】:
    fetch('api/orders', init)
          .then(response => response.json())
          .then(data => {
            if (!data.error) {
              that.setState({
                 ...confirmationDetail,
                 confirmationDetail: data,
                 cart: []
              });
            } else {
              Swal.fire(data.error);
            }
          });
    

    【讨论】:

      猜你喜欢
      • 2019-09-07
      • 2019-12-29
      • 1970-01-01
      • 2018-04-18
      • 2020-08-27
      • 2019-11-23
      • 2020-09-21
      • 1970-01-01
      • 2016-12-18
      相关资源
      最近更新 更多