简体   繁体   中英

React, Redux, Immutable - cannot access JSON key within mapStateToProps

Hopefully a really simple one (react newbie here!) but I cannot seem to access a specific key within the state property returned from a react/redux/immutable reducer.

Consider the following where I wish to return the value of state.api.authenticated :

function mapStateToProps(state) {
  console.log('DEBUG 1: ', JSON.stringify(state));
  console.log('DEBUG 2: ', JSON.stringify(state.api));
  console.log('DEBUG 3: ', JSON.stringify(state.api.authenticated));
  return {
    authenticated: state.api.authenticated
  };
}

This returns the following:

DEBUG 1:  {"modals":{},"routing":{"locationBeforeTransitions":null},"api":{"loading":false,"requests":{},"errors":{"last":null},"data":{"articles":[]},"authenticated":true},"articles":{"to_read_count":0},"form":{"signin":{"registeredFields".... (redacted for brevity)

DEBUG 2:  {"loading":false,"requests":{},"errors":{"last":null},"data":{"articles":[]},"authenticated":true}

DEBUG 3:  undefined

So clearly state.api.authenticated IS in the state object and yet I cannot access it!

Any advice much appreciated.


Edit 1: Reducer initial state definition:

const initialState = Map({
  loading: false,
  requests: OrderedMap({}),
  errors: Map({
    last: null
  }),
  data: Map({
    articles: List()
  }),
  authenticated: false
});

Reducer setting value:

case AUTH_USER:
      return state.set('authenticated', true);

SOLUTION: ok, thanks to the comments I found state.api.get worked:

const mapStateToProps = (state) => {
  return {
    authenticated: state.api.get('authenticated')
  };
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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