【问题标题】:react filter state by id if not set default value如果未设置默认值,则通过 id 反应过滤状态
【发布时间】:2016-05-30 03:26:29
【问题描述】:

我的状态如下:

Object {active: false, class: "myclass", id: 1}

我想在这里获得价值,例如:

{this.state.filter(cls => cls.id==1) ? 'anyclass'}

这里我想要 id 的值为 1,那么它应该返回我 myclass 如果没有,那么我想要一些像 anyclass 这样的默认值

我怎样才能做这样的过滤?

谢谢

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    {this.state.id === 1 ? this.state.class : 'anyclass'} 怎么样?

    【讨论】:

      【解决方案2】:

      我建议你使用 immutable.js 提供的地图数据结构:

      import {List, Map} from 'immutable'; // refer the require 
      
      var map = Map(data.reduce(function(previous, current) 
      { 
          previous[ current._id ] = current;
          return previous;
      }, {}));
      
      //then, you can directly fetch with id, and check your logic:
      var id='param'
      state.filter.get(id) === 1 ? state.class : 'anyclass'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-01
        • 2021-05-29
        • 1970-01-01
        • 2020-03-19
        相关资源
        最近更新 更多