【问题标题】:How to access to new state of useReducer inside custom hook's function如何在自定义钩子函数中访问 useReducer 的新状态
【发布时间】:2020-02-25 08:29:19
【问题描述】:

我有一个使用 useReducer 的自定义钩子。

function useMyCustomHook() {
   const [state, dispatch] = useReducer(EntityReducer, initialState);

   // console.log(state); // 1- state is up to date here

   const customDispatch = (action) => {
       dispatch({ ...action }); // first call EntityReducer by action.type

       //2- I use state and dispatch here(for example:use state for call an api, then dispatch response)
       // but the state is previous not new state?

       switch (action.type) {
           case "something":
               // use dispatch and state here                     
               return state;
       }
   }

   return [state, customDispatch];
}

使用自定义钩子:

function HomePage(props) {
    const [state, dispatch] = useMyCustomHook();

    // for example use dispatch on click a button

    return (<div>...</div>)
}

问题:statecustomDispatch 内部的 prev 状态。我该如何解决这个问题?

提前致谢。

【问题讨论】:

    标签: reactjs react-hooks use-reducer


    【解决方案1】:

    据我所知,您的状态在 react-hooks 中已经过时(被闭包捕获)。

    那么你有这些解决方案:

    1-useEffect 有依赖关系

    useEffect(() => {
     // state will be updated here
     // declare 'customDispatch' here
    }, [state,...]);
    

    2-useRefuseMyCustomHook 喜欢:

    const [state, dispatch] = useReducer(EntityReducer, initialState);
    const stateRef=useRef(state);
    
    useEffect(() => {
            stateRef.current=state;
    });
    
    const customDispatch = (action) => {
    // use state.current instead of state(state.current will be updated)
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-28
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 2017-08-04
      • 2019-10-17
      • 1970-01-01
      相关资源
      最近更新 更多