React-Redux Store未更新:mapStateToProps值显示为undefined问题
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:
Incorrect State Nesting
In yourUSER_DATAaction handler, you're accidentally nesting theusersarray inside anotherusersobject: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 */] }.Missing State Return
Redux reducers must return the new state for updates to take effect. Your current code only assignsstate = ...but doesn't return it—so the reducer ends up returningundefinedfor 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
usersarray in the state meansmapStateToPropscorrectly pulls in the user data instead of hitting anundefinednested 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

