【问题标题】:adding map function within map function is not displaying any items在地图功能中添加地图功能不显示任何项目
【发布时间】:2018-12-28 08:26:56
【问题描述】:

我有两组数据,它们是 json 文件中的项目数组。仅通过props.detailData.map 映射会显示内容。但是当我添加props.imageLinks.map 并将其映射到地图中以添加“a href”时,屏幕上不会显示任何内容。事实上,控制台中不会引发任何错误。怎么了?

import React from "react";


const Descriptions = (props) => {
   console.log(props.detailData)
   {/************["a", "b", "c", "d"]**********/}

   console.log(props.imageLinks)
   {/************["http://www.l.com", "http://www.m.com", "http://www.n.com", "http://www.o.com"]**********/}

   return (
       <div> 
          <div> 
             {props.imageLinks.map((l, i) =>
                {props.detailData.map((d, i) =>
                  <li key={i}>
                    {d} 
                    <div>
                      <a href={l}> view images </a>
                    </div>
                  </li>
                )}
             )}
         </div>
      </div>
    )
}

export default Descriptions;

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    如果您的目标是拥有 16 个 &lt;li&gt;,那么请使用上面 @JJJ 中的代码,因为每次迭代都会遍历每个数组 (4x4) 中的每一项。

    如果您的目标是拥有 4 个 &lt;li&gt;detailDataimageLinks,那么您最好的选择是像这样合并 2 个数组:

    const detailData = ["a", "b", "c", "d"];
    const imageLinks = ["http://www.l.com", "http://www.m.com", "http://www.n.com", "http://www.o.com"];
    let res = detailData.map((key, i) => {
        return [key, imageLinks[i]]
    });
    console.log(res);
    return (
    <div className="App">
    {res.map((l, i) => (
        <li key={i}>
            {l[0]} 
            <div>
            <a href={l[1]}> view images </a>
            </div>
        </li>
    ))}
    </div>
    

    显然有一些方法可以合并 2 个数组。这只是其中之一。

    【讨论】:

      【解决方案2】:

      内部 map 函数中的大括号表示一个函数块,而不是 JSX 模板语法。该函数不返回任何内容,这就是它也不显示任何内容的原因。去掉括号。

      {props.imageLinks.map((l, i) =>
          props.detailData.map((d, i) =>
            <li key={i}>
              {d} 
              <div>
                <a href={l}> view images </a>
              </div>
            </li>
          )
      )} 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-05
        • 1970-01-01
        • 1970-01-01
        • 2018-09-27
        • 2021-02-03
        • 2011-06-14
        • 2013-12-31
        相关资源
        最近更新 更多