React js 组件,map 有效,foreach 无效

IT技术 javascript reactjs dictionary foreach
2021-05-13 17:38:52

我有一个呈现标签的组件。它遍历 Map 并显示数据。我尝试使用 forEach 但它不起作用。但是,如果我将映射转换为数组,它就可以工作(foreach 也不适用于该数组)。我在这里错过了什么?

这有效:

render(){
    return(
        <div class="container">
            {Array.from(this.props.tags.values()).map((tag,i) => (
                <Tag
                    handleKeyDown={this.handleKeyDown.bind(this)}
                    handleBlur={this.handleBlur.bind(this)}
                    handleTouchTap={this.handleTouchTap.bind(this)}
                    handleRequestDelete={this.handleRequestDelete.bind(this)}
                    tag={tag}
                    key={i}
                />
            ))}
        </div>
    )
}

这不会:

render(){
    return(
        <div class="container">
            {this.props.tags.forEach((tag,i) => (
                <Tag
                    handleKeyDown={this.handleKeyDown.bind(this)}
                    handleBlur={this.handleBlur.bind(this)}
                    handleTouchTap={this.handleTouchTap.bind(this)}
                    handleRequestDelete={this.handleRequestDelete.bind(this)}
                    tag={tag}
                    key={i}
                />
            ))}
        </div>
    )
}
1个回答

Map#forEach不返回新数组。它们都按照您的预期工作,用于Array#map构建一个从旧数组映射的新数组。React.createElement需要将其子项作为参数列表或数组。一般来说,你Map更像是一个普通的而Object不是一个数组,也就是说,如果你想单独管理它的值,你可以将它转换为一个数组。

您的Array.from使用是一个很好的方法。这就是我通常使用Maps 的方式。如果您想使用它变得真正现代,并避免其中一次迭代(尽管我只能想象这对于最极端的情况很重要),您始终可以将迭代器函数应用于 Map 的值,然后在其上展开迭代器。

render() {
  const asTags = function* () {
    for (const [key, tag] of this.props.tags) {
      yield <Tag tag={tag} key={key} />;
    }
  };

  return (
    <div class="container">
      {[...asTags()]}
    </div>
  );
}

生成器函数是一个简单的迭代器,它yield包含它在 Map 中循环的每个条目。我只在那里使用数组,因为我不完全确定如何在 JSX 中传播参数(我不使用 JSX 的一个原因)。如果您已React.createElement导入 as ce,则可以简单地ce('div', { class: 'container' }, ...asTags())在渲染中