【发布时间】:2019-08-23 22:21:07
【问题描述】:
我正在使用 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;
问题是,如上面的评论所述,为什么上下文提供者的otherFunction 中的state.stateUpdated 仍然是false,我如何通过同一函数的最新更改访问状态?
【问题讨论】:
标签: javascript reactjs react-hooks react-context