javascript - React 中的 Axios 异步等待

标签 javascript async-await axios

我正在尝试执行一些 get 和 post 请求,不知何故状态更新较晚(应该是 .get,然后是 .post)

async componentDidMount() {

    const {destination, weight} = this.state;


    axios.get(`https://myapi`)
        .then(res => {
            const customer = res.data;

            this.setState({ customer,
                destination: customer[0].address[0].city,
            }
        })

   axios.post(`https://myapi`, {destination, weight})
        .then((post)=>{
          const delivery = post.data;
            this.setState({ delivery,
              cost: delivery[0].cost[0].value
             });
        });

        return post;
}

状态已更新,但不知何故帖子出现错误,应填写目的地。我发现这个问题的解决方案是使用异步等待。我尝试实现它,但它不起作用。

这是我尝试过的

async componentDidMount() {

        const {destination, weight} = this.state;


        axios.get(`https://myapi`)
            .then(res => {
                const customer = res.data;

                this.setState({ customer,
                    destination: customer[0].address[0].city,
                }
            })

const post = await axios.post(`https://api.cashless.vip/api/cost`, {destination, weight})
            .then((post)=>{
          console.log(this.state.destination);
              const delivery = post.data;
                this.setState({ delivery,
                  cost: delivery[0].cost[0].value
                 });
            });

            return post;
}

我尝试控制台记录目标状态,是的,它确实已更新。我做的异步等待错误吗?感谢您的帮助!

最佳答案

try{
   let res = await axios.get(`https://myapi`);
   if (res) {
     const customer = res.data;
     this.setState({ customer,
        destination: customer[0].address[0].city,
     });
     const postRes = await axios.post(`https://api.cashless.vip/api/cost`);
     if (postRes) {
       const delivery = post.data;
         this.setState({ delivery,
           cost: delivery[0].cost[0].value
         });
     }
   }
}catch (err) {
  console.log(err);
}

如果您想在外部使用帖子(由您决定)。

关于javascript - React 中的 Axios 异步等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56363571/

相关文章:

javascript - 如何检查此 JavaScript 数组中是否存在值?

asynchronous - 即使范围拥有变量的所有权,引用仍被保留而无法使用

c# - 在 FormClosing 事件中等待异步函数

reactjs - Axios 不使用 https 的代理设置

axios - 如何将 auth header 添加到 axios hooks 请求?

javascript - VueJS 数据属性在已安装函数中返回未定义

javascript - 通过 AJAX 加载 javascript 元素

javascript - 如何使用 JavaScript 使 Repeater 内的 TextArea 在单击按钮时显示?

javascript - React leaflet map 库中的GeoJSON样式

python - 为什么不将函数声明为 types.CoroutineType 的异步函数?