如何暂停功能,直到响应返回并设置状态为止



我正在运行一个具有API调用的函数,该功能带回了我用来设置状态的响应,然后触发另一个使用刚刚更新的状态的函数。问题在响应返回并更新状态

之前,第二个功能正在运行。

我尝试过。然后我认为应该有效

import React from "react";
import API from "../../utils/API"
class Content extends React.Component {
    state={
        postID:"",
        statusPost:""
    }
    submitPost = () => {
        API.savePost({
            content: this.state.statusPost,
            post_by: this.props.userInfo.firstname + this.props.userInfo.lastname
        })
        .then(console.log(this.submitPost))
        .then(res => {
            this.setState({ postID:res.data._id })
            console.log(this.state)
        })
            .then(this.addPostID())
            .catch(err => console.log(err));
    }

    addPostID = () => {
    API.postID({
        _id:  this.props.userInfo.user_ID,
        post:this.state.postID
      })
      .then(res => console.log(res))
      .catch(err => console.log(err));
    }
}

这里的问题是 setState本身是异步的。它更好地用于基于状态更改渲染React组件,但不是用于在函数调用之间传输数据。因此,最好以这种方式重构编码

submitPost = () => {
    API.savePost({
        content: this.state.statusPost,
        post_by: this.props.userInfo.firstname + this.props.userInfo.lastname
    })
    .then(console.log(this.submitPost))
    .then(res => {
        this.setState({ postID:res.data._id })
        console.log(this.state)
        this.addPostID(res.data._id); // As state will not be updated on this point
    })
        .catch(err => console.log(err));
}
addPostID = (postID) => {
API.postID({
    _id:  this.props.userInfo.user_ID,
    post:postID // Use argument and not state here
  })
  .then(res => console.log(res))
  .catch(err => console.log(err));
}

解决此问题的替代方法可能是使用setState函数的第二个参数,这是在状态更新后将调用的回调。

例如

this.setState({ postID:res.data._id }, () => this.addPostID()); // Now addPostId will be called after state updated

最新更新