问题描述
我试图在db.json的最后一个元素上使用axios补丁请求。 为此,我将“ id”的状态设置为json中数据的长度。如果我用控制台记录我的状态,它将给我正确的号码。但是,如果将状态放入URL,则在那里什么也不会发生。使用正常数字代替状态是可行的。我在做什么错了?
handleSubmit = event => {
const sub = this.newsletter();
axios.get('http://localhost:3001/posts')
.then(res => {
this.setState({id: res.data.length});
console.log(this.state.id);
});
if(sub){
axios.patch(`http://localhost:3001/posts/${this.state.id}`,{
newsletter: 'yes'
})
.then(res => {
console.log(res);
console.log(res.data);
})
}
}
解决方法
等待状态由您的ID更新,然后调用第二个补丁请求。因为设置状态需要一些时间。
handleSubmit = event => {
const sub = this.newsletter();
axios.get('http://localhost:3001/posts')
.then(res => {
this.setState({id: res.data.length},() => {
// NOW OUR STATE HAVE THE PROPER ID
if(sub){
axios.patch(`http://localhost:3001/posts/${this.state.id}`,{
newsletter: 'yes'
})
.then(res => {
console.log(res);
console.log(res.data);
})
}
}
});
});
,
setState
处于非同步状态。您可以将其视为enqueueSettingTheState
。因此,当第一个then
块完成时,我们不确定状态是否已设置。
您可以做的就是不要在州内存储任何东西,然后继续呼叫patch
:
handleSubmit = event => {
const sub = this.newsletter();
axios.get("http://localhost:3001/posts").then(res => {
// Read the value you want
let id = res.data.length;
if (sub) {
// Use the value without storing it
return axios.patch(`http://localhost:3001/posts/${id}`,{
newsletter: "yes"
})
.then(res => {
console.log(res);
console.log(res.data);
});
}
});
};