【问题标题】:How to access to a state in the render part with for loop?如何使用 for 循环访问渲染部分中的状态?
【发布时间】:2021-05-21 02:40:16
【问题描述】:

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

【问题讨论】:

    标签: reactjs for-loop state render


    【解决方案1】:

    for-loop 结构在 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 - 渲染数据列表的官方文档

    【讨论】:

    • 谢谢,它对我有用。我是 JS 的新手。感谢您编写工作代码。
    • @LiLian 欢迎。我还链接了有关渲染数组的 React 文档,我强烈建议您尽可能多地阅读 React 文档。它们的编写和维护都非常出色。欢迎使用 React,祝你好运。
    【解决方案2】:

    你应该这样做:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-29
      • 2020-11-14
      • 1970-01-01
      • 2014-07-10
      • 2018-01-08
      • 2014-05-31
      • 2017-12-30
      • 2014-08-28
      相关资源
      最近更新 更多