javascript - React useReducer 不会在 React 上下文中更新状态
问题描述
React useReducer 不会在 React 上下文中更新状态。但在返回部分状态数据正确呈现。这是示例:
上下文.js
const globalContext = React.createContext();
const initialState = {
statuses: null,
};
const globalReducer = (state, action) => {
switch (action.type) {
case 'SET_STATUSES':
return { ...state, statuses: action.payload };
default:
return state;
}
};
export const GlobalState = ({ children }) => {
const [state, dispatch] = React.useReducer(globalReducer, initialState);
return <globalContext.Provider value={{ state, dispatch }}>{children}</globalContext.Provider>;
};
export const useGlobalState = () => {
const context = React.useContext(globalContext);
return context;
};
comeChild.js
const { state, dispatch } = useGlobalState();
const testFn = () => {
console.log(state); // -> {statuses: null} :here is issue
};
React.useEffect(() => {
console.log(state); // -> {statuses: null} :as expected
dispatch({ type: 'SET_STATUSES', payload: 'test str' });
console.log(state); // -> {statuses: null} :here is issue
testFn();
setTimeout(() => {
console.log(state); // -> {statuses: null} :here is issue
}, 3000);
}, []);
return <div>
{state.statuses && <div>{state.statuses}</div>}// -> 'test str'
</div>;
可能是什么问题?
解决方案
我对上下文和 useReducer 很陌生,但我的猜测是 React 中的良好状态“逻辑”。React 更新状态是异步的而不是同步的,这可能会导致这些行为。
您的 reducer 和 context 显然有效,因为它在您的 return 语句中输出正确的状态。这是因为你的state.statuses &&
条件,说明你要返回 div WHEN state.statuses "exist" 可以这么说。
所以对我来说这看起来没什么问题,只是 React 是 React 与状态更新。
您可以console.log(action.payload)
在减速器中查看“test str”何时进入减速器操作。
推荐阅读
- javascript - React - 从相对 URL 加载图像(通过 Web API)
- angular - 角度可观察
对象始终为空 - linux - tar 命令生成的文件列表
- javascript - 自动关闭 HTML 页面
- android - NullPointerException:尝试获取空数组的长度
- r - left_join 但将 NA 视为通配符匹配
- javascript - 当只剩下一个索引时,Array.splice 不工作
- vuejs3 - 如何在 vue 3 中通过类绑定传递参数并相应地更改按钮的颜色?
- google-maps - 自动完成谷歌地址api
- android - 如何在 google play 控制台上运行多个封闭测试?