【问题标题】:map function isn't returning the valuesmap 函数没有返回值
【发布时间】:2020-04-30 17:08:37
【问题描述】:

我正在尝试返回存储在数据库中的 nextjs 组件中的类别。 我正在使用地图功能返回,但它不起作用。

const showAllCategories = () =>{
      return  categories.map((c,i)=>{
                <Link  key={i} href ={`/categories}`} >
                    <a className="btn btn-outline-primary mr-1 ml-1 mt-3"> {c.name }</a>
                </Link>
        })
    }

我试图在 html 的部分标签内返回类别名称

<section>
                            {/* <p>Show categories and tags</p> */}
                            <div className="pb-5">
                                    {JSON.stringify(showAllCategories())}
                                {showAllCategories()}
                                {showAllTags()}

                            </div>
                        </section>

我尝试使用 JSON.stringyfy 进行调试,但它显示 [null,null,null,null,null,null,null,null]

【问题讨论】:

    标签: reactjs function dictionary return next.js


    【解决方案1】:

    正如其他人所说,您缺少 return 关键字。

    ES6 你可以通过省略左括号{ 在一行中返回内容。我认为这会让很多人感到困惑。举这两个例子。

    categories.map((c, i) =&gt; c.name);

    上述自动返回 c.name。

    categories.map((c, i) =&gt; { return c.name; });

    与此相同,但打开括号{ 后,您需要在其中返回。

    【讨论】:

    • 谢谢你,它现在工作了,它也解决了我的疑惑
    【解决方案2】:

    你缺少return关键字,应该是这样的:

    const showAllCategories = () => {
      return  categories.map((c,i)=> {
          return (<Link  key={i} href={`/categories}`} >
              <a className="btn btn-outline-primary mr-1 ml-1 mt-3"> {c.name }</a>
          </Link>
        );
      })
    }
    

    【讨论】:

      【解决方案3】:
      const showAllCategories = () => {
        return categories.map((c, i)=> {
          // you forgot return here
          return (
                  <Link  key={i} href ={`/categories}`} >
                      <a className="btn btn-outline-primary mr-1 ml-1 mt-3"> {c.name }</a>
                  </Link>
             )
          })
      }
      

      或者更短一点 -

      const showAllCategories = () => categories.map((c, i) => (
          <Link key={i} href={`/categories}`}>
              <a className="btn btn-outline-primary mr-1 ml-1 mt-3"> {c.name}</a>
          </Link>
      );
      

      【讨论】:

        猜你喜欢
        • 2020-08-17
        • 2017-06-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-06
        相关资源
        最近更新 更多