【问题标题】:How do i render the Array value by comparing another array in ReactJs如何通过比较 ReactJs 中的另一个数组来呈现数组值
【发布时间】:2020-10-13 08:19:38
【问题描述】:

我有下面给出的道具数组

this.props.fruits= [
  {
    source: "Apple",
    code: 101,
  },
  {
    source: "banana",
    code: 105,
  },
  { source: "Mango",
    code: 107,
  },
];

在我的状态下,我必须保存代码仅用于将其发送到后端,我的状态如下所示

this.state ={
   myfruits:[101,105]
}

我必须在 DOM 元素中呈现 myfruits 名称 渲染 DOM 元素的示例

My Fruits : Apple , banana

【问题讨论】:

    标签: javascript arrays reactjs rendering


    【解决方案1】:

    您可以组合使用 filter、map 和 join 来实现此功能。

    示例不是 React,而是向您展示了如何实现这一点。

    const fruits = [
      {
        source: "Apple",
        code: 101,
      },
      {
        source: "banana",
        code: 105,
      },
      { source: "Mango",
        code: 107,
      },
    ];
    
    const state = [101, 105];
    
    const getFruitNames = () => fruits
      .filter(({ code }) => state.includes(code)) // Get all fruit objects where the code is also in state
      .map(({ source }) => source) // Only return the source (name)
      .join(", "); // Turn into a comma seperated string
    
    console.log(`My Fruits: ${getFruitNames()}`);

    【讨论】:

    • .join(", ") 方法在渲染时不起作用,返回为 [object,object].. 有什么解决方案
    • @Sanjaikumar 这意味着您加入的项目是对象。您只需返回您要显示的名称,如果您有更多代码我可以尝试调试它。
    【解决方案2】:

    您可以使用过滤器和映射方法的组合,

    this.props.fruits.filter((fruit) => this.state.myfruits.includes(fruit.code))
              .map((fruit) => fruit.source)
    

    这应该可以解决您的问题。您可以阅读有关地图和过滤器的更多信息here。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-30
      • 2013-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 2017-06-08
      相关资源
      最近更新 更多