Reactjs 如何暂停函数,直到返回响应并设置状态
我正在运行一个函数,该函数具有一个API调用,该调用返回一个响应,我使用该响应设置状态,然后触发另一个函数,该函数使用刚刚更新的状态。第二个函数在响应返回并更新状态之前运行的问题 我已经试过了。然后我觉得应该行得通Reactjs 如何暂停函数,直到返回响应并设置状态,reactjs,api,promise,pause,Reactjs,Api,Promise,Pause,我正在运行一个函数,该函数具有一个API调用,该调用返回一个响应,我使用该响应设置状态,然后触发另一个函数,该函数使用刚刚更新的状态。第二个函数在响应返回并更新状态之前运行的问题 我已经试过了。然后我觉得应该行得通 import React from "react"; import API from "../../utils/API" class Content extends React.Component { state={ postID:"", st
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