为什么在更改setstate的行时状态未更改

时间:2020-02-03 22:45:34

标签: reactjs

请需要您的帮助, 当将下面的行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)
    )

}

1 个答案:

答案 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);
    };
}