Javascript useState返回初始值而不是更新值

Javascript useState返回初始值而不是更新值,javascript,reactjs,react-redux,react-hooks,Javascript,Reactjs,React Redux,React Hooks,我强制下面的代码在catch块中运行,它将getFoodCategoriesFailed设置为true,之后当它转到最终块时,它仍然将getFoodCategoriesFailed显示为false,这是它的初始值。有人能指出我做错了什么并帮我改正吗 const [getFoodCategoriesFailed, setGetFoodCategoriesFailed] = useState(false); const getCategories = async (url) => { c

我强制下面的代码在
catch
块中运行,它将
getFoodCategoriesFailed
设置为
true
,之后当它转到
最终
块时,它仍然将
getFoodCategoriesFailed
显示为
false
,这是它的初始值。有人能指出我做错了什么并帮我改正吗

const [getFoodCategoriesFailed, setGetFoodCategoriesFailed] = useState(false);

const getCategories = async (url) => {
  const { request } = await requestor.get({ url });

  request.then((response) => {
    setFoodCategories(response);
    setGetFoodCategoriesFailed(false);
  }).catch(() => {
    setFoodCategories(undefined);
    setGetFoodCategoriesFailed(true);
  }).finally(() => {
    onFoodCategoriesRetrieved(getFoodCategoriesFailed, foodCategories?.food_categories);
  });
};

useEffect(() => {
  const url = "xyz";
  getCategories(url);
}, [foodCategories]);


useState不会同步更改

如果要同步使用useState,请使用下面的代码

import { useState, useRef, useEffect } from 'react';

export default function useStateCallback(initialState) {
  const [state, setState] = useState(initialState);
  const cbRef = useRef(null); // mutable ref to store current callback

  // eslint-disable-next-line no-shadow
  const setStateCallback = (state, cb) => {
    cbRef.current = cb; // store passed callback to ref
    setState(state);
  };

  useEffect(() => {
    // cb.current is `null` on initial render, so we only execute cb on state *updates*
    if (cbRef.current) {
      cbRef.current(state);
      cbRef.current = null; // reset callback after execution
    }
  }, [state]);

  return [state, setStateCallback];
}


我不是专家,所以如果这没有帮助,我道歉,但是。。。有几件事我可以试试:

  • 考虑将onFoodCategoriesRetrieved移动到(或作为新的)useEffect调用(并将getFoodCategoriesFailed添加到依赖项列表)是否有意义

  • 比如:


  • 所以在添加了上面的代码之后,我是否只需要更新下面的代码行const[getFoodCategoriesFailed,setGetFoodCategoriesFailed]=useStateCallback(false)```
    const[state,setState]=useStateCallback(0)
    constonclick=()=>setState(prev=>prev+1,data=>console.log(data))
    const getCategories = async (url) => {
      const { request } = await requestor.get({ url });
      let localFoodCategories = undefined;
      let localGetFoodCategoriesFailed = true;
      
      request.then((response) => {
        localFoodCategories = response;
        localGetFoodCategoriesFailed = false;
      }).catch(() => {
      }).finally(() => {
        setFoodCategories(localFoodCategories);
        setGetFoodCategoriesFailed(localGetFoodCategoriesFailed);
        onFoodCategoriesRetrieved(localGetFoodCategoriesFailed, localFoodCategories?.food_categories);
      });
    };