React useReducer 不要在 React 上下文中更新状态


React useReducer不更新React上下文中的状态。但在返回部分中,状态数据呈现正确。这是样品:

context.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相当陌生,但我的猜测是好的ol‘state"逻辑";在React中。React更新状态异步而非同步,这可能导致这些行为。

您的reducer和上下文显然有效,因为它在return语句中输出正确的状态。这是因为您的state.statuses &&条件,表示您希望返回div WHEN state.status"存在";可以这么说。

所以对我来说,这看起来没有任何问题,只是React是React的状态更新。

您可以在reducer中console.log(action.payload)查看"test-str"何时进入reducer操作。

最新更新