【问题标题】:How to loop an array inside an array with React如何使用 React 在数组中循环数组
【发布时间】:2017-06-02 01:56:48
【问题描述】:

您好,我有一些数据正在尝试显示,看起来像这样

snapshot

在 Poll 数组内部有一个 Options 数组。 当我已经映射 Poll 数组时,如何显示带有 react 的选项数组?这是我到目前为止所拥有的:

renderPost(posts){

        return posts.map((post) => {
        return (
            <div>
            <h3>{post.question}</h3>


            </div>
               );
        });
    }

【问题讨论】:

    标签: arrays reactjs


    【解决方案1】:

    类似

    renderPost(posts){
      return posts.map(post =>
        <div>
          <h3>{post.question}</h3>
          <ul>
            {post.options.map(option => 
              <li>{option.title}</li>
            )}
          </ul>
        </div>
      )
    }
    

    【讨论】:

    • 嘿,感谢您的回复,但我得到“无法读取未定义的属性 'map'”
    • 我不得不猜测您的数据模型,您需要根据您的特定需求对其进行调整
    【解决方案2】:

    在循环生成 jsx 元素时,你永远不要忘记为它们添加一个键。键应该是唯一的,并且键应该来自数据,如果您的数据不包含每个对象的唯一 ID,则使用索引作为键,如下所示

    作为数据键的唯一 id

    return posts.map(post =>
        <div key={post.id}>
          <h3>{post.question}</h3>
          <ul>
            {post.options.map(option => 
              <li key={option.id}>{option.title}</li>
            )}
          </ul>
        </div>
      )
    

    如果数据数组中没有唯一ID,则使用索引作为键

    return posts.map((post, index) =>
        <div key={`Key${index}`}>
          <h3>{post.question}</h3>
          <ul>
            {post.options.map((option, i) => 
              <li key={`Key${i}`}>{option.title}</li>
            )}
          </ul>
        </div>
      )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-29
      • 2012-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多