无法读取上下文提供程序中useReducer hook更新的状态

问题描述 投票:1回答:1

我使用useReducer钩来管理我的状态,但似乎我在上下文提供程序中读取更新状态时遇到问题。

我的上下文提供程序负责获取一些远程数据并根据响应更新状态:

import React, { useEffect } from 'react';
import useAppState from './useAppState';


export const AppContext = React.createContext();

const AppContextProvider = props => {
  const [state, dispatch] = useAppState();

  const initialFunction = () => {
    fetch('/some_path')
      .then(res => {
        dispatch({ type: 'UPDATE_STATE', res });
      });
  };

  const otherFunction = () => {
    fetch('/other_path')
      .then(res => {
        // why is `state.stateUpdated` here still 'false'????
        dispatch({ type: 'DO_SOMETHING_ELSE', res });
      });
    }
  };

  const actions = { initialFunction, otherFunction };

  useEffect(() => {
    initialFunction();
    setInterval(otherFunction, 30000);
  }, []);

  return (
    <AppContext.Provider value={{ state, actions }}>
      {props.children}
    </AppContext.Provider>
  )
};

export default AppContextProvider;

useAppState.js非常简单:

import { useReducer } from 'react';


const useAppState = () => {
  const reducer = (state, action) => {
    switch (action.type) {
      case 'UPDATE_STATE':
        return {
          ...state,
          stateUpdated: true,
        };
      case 'DO_SOMETHING_ELSE':
        return {
          ...state,
          // whatever else
        };
      default:
        throw new Error();
    }
  };


  const initialState = { stateUpdated: false };

  return useReducer(reducer, initialState);
};


export default useAppState;

问题是,正如上面的评论所述,为什么state.stateUpdated在上下文提供者的otherFunction仍然是false,我怎么能访问具有相同功能的最新变化的状态?

javascript reactjs react-hooks react-context
1个回答
1
投票

state will never change in that function

state在该函数中永远不会改变的原因是state仅在重新渲染时更新。因此,如果您想访问state,您有两种选择:

  1. useRef看到state的未来价值(你必须修改你的减速器才能使这个工作)
const updatedState = useRef(initialState);
const reducer = (state, action) => {
  let result;
  // Do your switch but don't return, just modify result

  updatedState.current = result;
  return result;
};

return [...useReducer(reducer, initialState), updatedState];
  1. 您可以在每次状态更改后重置setInterval,以便它可以看到最新的状态。但是,这意味着您的间隔可能会中断很多。
const otherFunction = useCallback(() => {
  fetch('/other_path')
    .then(res => {
      // why is `state.stateUpdated` here still 'false'????
      dispatch({ type: 'DO_SOMETHING_ELSE', res });
    });
  }
}, [state.stateUpdated]);

useEffect(() => {
  const id = setInterval(otherFunction, 30000);
  return () => clearInterval(id);
}, [otherFunction]);
© www.soinside.com 2019 - 2024. All rights reserved.