请需要您的帮助,
当将下面的行setloadingstate(prevState => prevState = false)
更改为promise内的箭头函数时,将可以正常工作,但按以下方式运行时,它将不能正常工作,并且状态保持为false,是否有解释?
const IngredientsHandler=(ingredients)=>{
setloadingstate(prevState => prevState = true)
fetch('https://ingredients.firebaseio.com/ig.json',{
method:'POST',
body:JSON.stringify(ingredients),
headers:{
ContentType:'application/json'
}
}).then(response => {
return response.json()
},
)
.then(
responseData => {
setIngredientsState((prevState) => ([...prevState,{id:responseData.name,...ingredients}]))
},
setloadingstate(prevState => prevState = false)
)
}
答案 0 :(得分:2)
不确定什至不使用prevState = true
值时为何在setloadingstate
中使用prevState
。试试这个
const IngredientsHandler=(ingredients)=>{
setloadingstate(true);
fetch('https://ingredients.firebaseio.com/ig.json',{
method:'POST',
body:JSON.stringify(ingredients),
headers:{
ContentType:'application/json'
}
}).then(response => {
return response.json();
}).then(responseData => {
setIngredientsState((prevState) => ([...prevState,{id:responseData.name,...ingredients}]));
}).finally(() => {
setloadingstate(false);
});
}
async
/ await
更干净
const IngredientsHandler= async (ingredients)=>{
setloadingstate(true);
try {
const response = await fetch('https://ingredients.firebaseio.com/ig.json',{
method:'POST',
body:JSON.stringify(ingredients),
headers:{ ContentType:'application/json'}
});
const responseData = await response.json();
setIngredientsState((prevState) => ([...prevState,{id:responseData.name,...ingredients}]));
} catch(ex) {
console.error({ ex }); // handle error(s)
} finally {
setloadingstate(false);
};
}