在ReactJS的Render函数中循环

时间:2016-10-25 00:28:34

标签: javascript reactjs

我可能知道下面的代码有什么问题吗?我认为<TextNote>标记的循环中出现了问题,但由于没有错误消息,我无法说出错误。谢谢

编辑仅供参考,仅渲染按钮,根本不渲染TextNote。 TextNote是另一个JS文件,它本身可以很好地工作。

render() {
return (
  <div className="textBoard">
    {this.state.textNotes.forEach( (note) => {
      return (<TextNote key={note.id}
                  id={note.id}
                  onChange={this.update}
                  onRemove={this.remove}>
              {note.note}
      </TextNote>)
    }
    )}
    <button onClick={() => this.add('New Text')}>ADD</button>
  </div>
)}

2 个答案:

答案 0 :(得分:0)

forEach不会return。请改用map

render() {
return (
  <div className="textBoard">
    {this.state.textNotes.map( (note) => {
      return (<TextNote key={note.id}
                  id={note.id}
                  onChange={this.update}
                  onRemove={this.remove}>
              {note.note}
      </TextNote>)
    }
    )}
    <button onClick={() => this.add('New Text')}>ADD</button>
  </div>
)}

答案 1 :(得分:0)

您也可以使用forEach方法,但方式稍有不同。

render(){
  const items = [];
  this.state.textNotes.forEach((note) => {
    items.push(<TextNote // instead of return push it in an array
                 key={note.id}
                 id={note.id}
                 onChange={this.update}
                 onRemove={this.remove}>
                {note.note}
              </TextNote>
  })
  return <div>
    {items}
  </div>
}

我还建议您使用map代替forEach,希望它可以帮助您