所以,我想在通过 http 请求将这些状态发送到后端之前更改我的 props 状态,但是 axios 在我的 if 语句代码执行之前发送这些状态。我不明白这个异步的事情。这是代码
login(){
const url = 'https://myapi.execute-api.ap-southeast-1.amazonaws.com/stage/resource';
this.setState(()=>{
if (this.state.email.indexOf('@') == -1){
return {email: ''}
} else {
return {username: ''}
}
})
axios.post(url, this.state).then(response => {
if (response.data["message"])
this.setState({message: response.data["message"]})
else
this.setState({message: response.data["token"]})
})
}
有人有解决办法吗?
最佳答案
你可以这样做。首先设置状态,然后完成 axios 请求。 setState
函数的第二个参数是回调。
另请参阅 react
文档:https://reactjs.org/docs/react-component.html#setstate
login(){
const url = 'https://myapi.execute-api.ap-southeast-1.amazonaws.com/stage/resource';
this.setState(()=>{
if (this.state.email.indexOf('@') == -1){
return {email: ''}
}
else {
return {username: ''}
}
},() => {
axios.post(url, this.state).then(response => {
if (response.data["message"])
this.setState({message: response.data["message"]})
else
this.setState({message: response.data["token"]})
})
});
}
关于javascript - 我想在进行 axios http 请求之前 setState,但不能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58949607/