You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React-Redux Store未更新:mapStateToProps值显示为undefined问题

Fixing Redux Store Update & undefined User Value in React-Redux

Hey there, let's walk through why your Redux store isn't updating correctly and why user is showing up as undefined in your component.

The Root Causes

Looking at your code, there are two critical issues in your userReducer that are breaking things:

  1. Incorrect State Nesting
    In your USER_DATA action handler, you're accidentally nesting the users array inside another users object:

    let newState={ users: [...state.users, ...action.payload] }
    state = {...state,users: newState }
    

    This creates a state structure like { users: { users: [/* user objects */] } } instead of the intended flat { users: [/* user objects */] }.

  2. Missing State Return
    Redux reducers must return the new state for updates to take effect. Your current code only assigns state = ... but doesn't return it—so the reducer ends up returning undefined for this action (except for the initial state), which means the store never actually updates.

Step-by-Step Fix

Let's fix the reducer first, since that's the core problem:

const defaultUserState = { users: [] };
const userReducer = (state = defaultUserState, action) => {
  switch(action.type){
    case actionType.USER_DATA:
      console.log("update_user_begins", action, action.payload);
      // Merge existing users with the payload directly
      const updatedUsers = [...state.users, ...action.payload];
      // Return a new state object with the updated users array
      return { ...state, users: updatedUsers };
    // Always handle unhandled actions by returning the current state
    default:
      return state;
  }
};

Next, adjust your mapStateToProps to match the corrected state structure (no more nested users access):

const mapStateToProps = state => ({ 
  user: state.usersR.users // Now directly access the users array
});

Why This Works

  • By returning the new state object in the reducer, Redux recognizes the update and triggers a re-render of your component.
  • The flat users array in the state means mapStateToProps correctly pulls in the user data instead of hitting an undefined nested property.

After making these changes, when you log user in your component's render method, you should see the array of user objects you're expecting.

内容的提问来源于stack exchange,提问作者Shashiwadana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:14:00