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

How to access to a state in the render part with for loop?

我在状态中有一个数组,我想用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>
    )
}

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 - 渲染数据列表的官方文档

你应该这样做:

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

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