简体   繁体   English

useSelector 在分派动作 React Redux 后不更新

[英]useSelector not updating after dispatching an action React Redux

I know there are already a couple of questions similar to this, but none of the solutions provided are working for me.我知道已经有几个与此类似的问题,但所提供的解决方案都不适用于我。 I am dispatching an action in my React Native component, but when I try to access the state afterwards with useSelector, it is still just the previous state, not the updated one.我正在我的 React Native 组件中调度一个动作,但是当我之后尝试使用 useSelector 访问状态时,它仍然只是之前的状态,而不是更新的状态。

My component:我的组件:

const userSettings = useSelector((state: any) => state.user.settings);

const loadUserSettings = async () => {
    await dispatch(userActions.fetchUserSettings());
}

const checkUserEnabled = async () => {
    await loadUserSettings();
    
    // The old state shows here rather than the updated one
    console.log(userSettings.enabled)
}

and this is my reducer:这是我的减速器:

const initialState = {
    settings = UserSettings,
};

export default (state = initialState, action) => {
    switch (action.type) {
        case SET_USER_SETTINGS:
            return {
                ...state,
                settings: action.settings,
            };
        default:
            return state;
    }
};

userSettings is a stale closure , as Nicolas suggested you cannot dispatch an action and expect the state value to have changed immediately because a new state is created after every action and your current function is still using the old value of the state. userSettings 是一个陈旧的闭包,因为 Nicolas 建议您不能分派操作并期望状态值立即更改,因为在每个操作之后都会创建一个新状态,并且您当前的函数仍在使用状态的旧值。 When the component re renders it will be re rendered with the new state value.当组件重新渲染时,它将使用新的状态值重新渲染。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM