为了账号安全,请及时绑定邮箱和手机立即绑定

无法读取上下文提供者中的useReducer挂钩更新的状态

无法读取上下文提供者中的useReducer挂钩更新的状态

www说 2021-04-05 17:14:20
我正在使用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状态,而我又该如何使用同一功能的最新更改访问状态?
查看完整描述

1 回答

?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

state 永远不会改变该功能

该state功能永远不会改变的原因state是仅在重新渲染时才更新。因此,如果要访问,则state有两个选择:


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];

您可以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]);


查看完整回答
反对 回复 2021-04-15
  • 1 回答
  • 0 关注
  • 305 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号