【问题标题】:React, Redux, Immutable - cannot access JSON key within mapStateToPropsReact、Redux、Immutable - 无法访问 mapStateToProps 中的 JSON 键
【发布时间】:2019-08-01 14:15:36
【问题描述】:

希望是一个非常简单的(在这里反应新手!)但我似乎无法访问从 react/redux/immutable reducer 返回的 state 属性中的特定键。

考虑以下我希望返回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
  };
}

这将返回以下内容:

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

很明显state.api.authenticated 存在于state 对象中,但我无法访问它!

非常感谢任何建议。


编辑 1:Reducer 初始状态定义:

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

减速机设定值:

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

【问题讨论】:

  • 您尝试在组件中记录this.props.authenticated 吗?
  • 试试这个state.getIn(['api', 'authenticated'])
  • 谢谢@NicolaeMaties - getIn 不是用于地图吗?仅供参考,我刚刚添加了初始状态。 Authenticated 应该是一个布尔值。
  • 这个state.api.getIn(['authenticated']).toJS() 应该可以工作

标签: reactjs redux state immutable.js


【解决方案1】:

解决方案:好的,感谢我发现 state.api.get 工作的 cmets:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-15
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多