【问题标题】:useState returns initial value and not updated valueuseState 返回初始值而不是更新值
【发布时间】:2021-02-05 02:23:24
【问题描述】:

我强制下面的代码运行catch 块,它将getFoodCategoriesFailed 设置为true,之后当它转到finally 块时,它仍然将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]);

【问题讨论】:

    标签: javascript reactjs react-redux react-hooks


    【解决方案1】:

    useState 不会同步变化

    Is useState synchronous?

    如果你想同步使用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];
    }
    
    

    【讨论】:

    • 那么在添加上面的代码之后,我只需要更新下面的代码行吗? ``` const [getFoodCategoriesFailed, setGetFoodCategoriesFailed] = useStateCallback(false); ```
    • const [state, setState] = useStateCallback(0); const onClick= () => setState(prev => prev + 1, data => console.log(data))
    【解决方案2】:

    我不是专家,如果这没有帮助,我深表歉意,但是......我可能会尝试一些事情:

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

    2. 类似:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-17
      • 2022-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多