Redux无法正确映射State到Props,无法访问myValue值求助
Hey there, let's break down what's going on here and fix your issue step by step!
1. Understand the Immutable State Structure
Your project uses redux-immutable's combineReducers, which means your entire Redux store state is an Immutable Map—not a regular JavaScript object. From your console output, you can see this.props.myValue is a Map containing nested Maps like route, global, and language. Regular dot notation (e.g., this.props.myValue.global) won't work on Immutable structures—you need to use Immutable's built-in methods.
2. Update mapStateToProps to Target the Correct Value
Right now, you're passing the entire root state to myValue. Instead, you need to drill down to the myValue field inside the global reducer branch. Modify your mapStateToProps like this:
const mapStateToProps = (state) => { // Use Immutable's getIn() to access nested values return { myValue: state.getIn(['global', 'myValue']), // Alternative step-by-step approach: // const globalState = state.get('global'); // myValue: globalState.get('myValue') }; };
This will make this.props.myValue directly return the numeric value (0 or updated value) you need, no nested access required.
3. Fix the Reducer to Maintain Immutable State
Your appReducer (globalReducer) initializes with an Immutable Map via fromJS, but in the case 'Name' block, you return a plain JavaScript object. This breaks the Immutable structure and causes inconsistencies later. Update the reducer to preserve the Immutable state:
import { fromJS } from 'immutable'; const initialState = fromJS({ myValue: 0, }); function appReducer(state = initialState, action) { console.log(`The reducer is being found and here is the state: ${state}`, ' and the action: ', action); switch (action.type) { case 'Name': // Use Immutable's set() to return a new updated Map return state.set('myValue', action.payload); default: return state; } } export default appReducer;
This ensures the global branch of your state stays an Immutable Map, matching the root store's structure.
4. Verify Access in Your Component
Now in your App component, you can directly access the numeric value:
{console.log(`This is the component App props: ${this.props.myValue}`)} // Output will be: "This is the component App props: 0" (or your updated value)
These changes will let you properly access and update myValue while maintaining the consistency of your Immutable Redux state.
内容的提问来源于stack exchange,提问作者Milos

