如何使用 for 循环访问渲染部分中的状态?

时间:2021-02-18 06:50:36

标签: reactjs for-loop state render

我在 state 中有一个数组,我想用 for 循环一个一个地渲染这个数组。 我不知道如何获得数组的长度,知道吗? 感谢您的帮助。 这是我的代码:

this.state = {
    array: []
}
// here is the function to write data into array
render(){
   return(
         <div>
            for(let i = 0; i < this.state.array.length; i++) { //this line doesn't work, error with length part
               <p> {this.state.array[i]}</p> // this line will work if I wirte outside of loop
            }
          </div>
    )
}

2 个答案:

答案 0 :(得分:1)

for 循环结构在 JSX 中不像在 javascript 中那样工作,因为您没有在循环中返回任何内容。

只需使用 array.prototype.mapstate.array 映射到要为数组中的每个元素呈现的 JSX。通过映射状态,您无需担心数组长度,map 函数会处理它。

this.state = {
    array: []
}

render() {
  return (
    <div>
      {this.state.array.map((el, i) => (<p key={i}>{el}</p>))}
    </div>
  );
}

Lists and Keys - 用于呈现数据列表的官方文档

答案 1 :(得分:0)

你应该这样做:

render(){
   return(
         <div>
         {
              this.state.array.map((element, index) => {
                  return (
                        <p key={`key-${index}`}>{element}</p>
                  );
              })
         }
          </div>
    )
}

在 React 循环中渲染多个组件时不要忘记 key prop。

相关问题