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

我正在使用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状态,而我又该如何使用同一功能的最新更改访问状态?


www说
浏览 306回答 1
1回答

阿波罗的战车

state 永远不会改变该功能该state功能永远不会改变的原因state是仅在重新渲染时才更新。因此,如果要访问,则state有两个选择:useRef以查看的未来价值state(您必须修改减速器以使其正常工作)const updatedState = useRef(initialState);const reducer = (state, action) => {&nbsp; let result;&nbsp; // Do your switch but don't return, just modify result&nbsp; updatedState.current = result;&nbsp; return result;};return [...useReducer(reducer, initialState), updatedState];您可以setInterval在每次状态更改后重置您的状态,以便它可以看到最新状态。但是,这意味着您的间隔可能会中断很多。const otherFunction = useCallback(() => {&nbsp; fetch('/other_path')&nbsp; &nbsp; .then(res => {&nbsp; &nbsp; &nbsp; // why is `state.stateUpdated` here still 'false'????&nbsp; &nbsp; &nbsp; dispatch({ type: 'DO_SOMETHING_ELSE', res });&nbsp; &nbsp; });&nbsp; }}, [state.stateUpdated]);useEffect(() => {&nbsp; const id = setInterval(otherFunction, 30000);&nbsp; return () => clearInterval(id);}, [otherFunction]);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript