【问题标题】:Immutable JS - get a value inside a nested map不可变 JS - 在嵌套映射中获取值
【发布时间】:2017-11-17 15:53:24
【问题描述】:

我正在使用 immutableJS、React/Redux 并且我有这张地图,我需要获取 actions 的值,所以它会像 -> allRetrospectivesMap -> id -> current_stage - > actions

我有这个代码,它可以工作,但它超级难看,有没有更好的方法?

    class UserActionItems extends Component {
      render() {
        const { retrospectives } = this.props
        const actions = flatten(
          Object.keys(immutableHelpers.toJS(retrospectives))
          .map(key => retrospectives.get(key))
          .map(retro => immutableHelpers.toJS(retro.getIn(['current_stage', 'actions'])))
        ).value()

    return (
       <div> 
          <ActionsList
          actions={actions[0]}
          users={[]}
          />
       </div>
    )
  }
}

    const mapStateToProps = ({ allRetrospectivesMap }) => ({
      retrospectives: allRetrospectivesMap
    })

谢谢!!! :)

【问题讨论】:

    标签: javascript reactjs dictionary redux immutable.js


    【解决方案1】:

    您可以使用来自不可变 js 的 getIn() 方法来做到这一点。

    const id = getId() // you've id from somewhere
    const actions= state.getIn(['allRetrospectivesMap', id, 'current_stage', 'actions']); // Note: state is your immutable data.
    

    阅读更多关于它的信息here

    【讨论】:

    • 我怎样才能得到身份证?这就是我使用.map 的原因还有其他方法吗?
    • id 是您的数据/状态的一部分吗?
    • 哦,我刚刚这样做了: const id = Object.keys(retrospectives)[0] const actions= retrospectives.getIn([id, 'current_stage', 'actions']);它奏效了!非常感谢:D
    • 哦,抱歉 :( 它没用,它确实 localStorage.clear() 并且它停止工作 xD 哈哈。所以我只需要操作的第一个 id,这就是我尝试这个 const 的原因id = Object.keys(retrospectives)[0] const actions= retrospectives.getIn([id, 'current_stage', 'actions']) 而retrospectives 我将它作为道具传递: const mapStateToProps = ({ allRetrospectivesMap }) => ({ retrospectives: allRetrospectivesMap }) 对不起,我是 redux 的新手,你知道怎么回事吗?
    猜你喜欢
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 2021-08-05
    相关资源
    最近更新 更多