在 React 中遍历 Immutable Map 的键

Iterating through keys of Immutable Map in React

通过 Immutable.js Map 对象处理迭代的最佳做法是什么?这有效:

{stocks.map((stock,key)=>{
    return ( <h3>{key}</h3> )
})}

但在控制台中给出了警告 "warning.js:45 Warning: Using Maps as children is not yet fully supported. It is an experimental feature that might be removed. Convert it to a sequence / iterable of keyed ReactElements instead."

之前已经讨论过了,这个 link 提出了一些策略 https://github.com/facebook/immutable-js/issues/667 但它们对我来说似乎很笨拙。喜欢:

posts.entrySeq().map(o => 
     <Post value={o[1]} key={o[0]} />
)

有效,但感觉笨拙。有更自然的方法吗?

为什么不stock.keys()?因为它 returns 是一个 ES6 迭代器,所以你需要将它转换为一个数组才能在旧的 JS 版本中工作:Array.from(stock.keys())

let zoo = Immutable.fromJS({ 'dog': 1, 'cat': 2 })

zoo.keys().map((name, index) => <Animal name={ name } key={ index } />)

请注意,我避免将 key 作为变量,然后将 index 值作为 key 传递给子组件,这是因为 React 需要引用动态创建的组件,因此它可以在其 VirtualDOM 中正确处理它们。阅读更多关于 React 的 Dynamic Children.

自从您提出这个问题后,已在您参考的 github 问题上发布了更好的解决方案。 @vinnymac 建议:

posts.entrySeq().map( ([key, value]) => 
  <Post key={key} value={value} />
)

这很有效,因为 entrySeq() returns 一个 key/value 元组的序列,然后您可以在 .map() 回调的参数中对其进行解构。

edit 我现在明白你只是要钥匙。在那种情况下,如果你想使用 ImmutableJS map()keys() 如果你想使用 ES6 map()

,请使用 keySeq()

使用Immutable Map的reduce方法是更直接的方法。由于 React 需要一个数组,因此设置空数组的初始值并将 jsx 推入其中可以解决问题。也适用于不可变列表。

{
   stocks.reduce((jsxArray, stock, index) => {
      jsxArray.push(
        <h3 key={index}>{index}</h3>,
      )
      return jsxArray;
   }, [])
}