map函数没有返回值

问题描述 投票:0回答:2

我试图返回存储在数据库中的Nextjs组件中的类别,我使用map函数来返回,但它不起作用。

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标签中返回分类名称。

<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
2个回答
0
投票
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>
);

1
投票

你缺少了返回关键字,应该是这样的。

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>
    );
  })
}

1
投票

就像其他人说的,你缺少了返回关键字。

在ES6中,你可以通过省略开括号,在一行中返回东西。{. 我想这就造成了很多人的困惑。以这2个例子为例。

categories.map((c, i) => c.name);

上面的自动返回c.name。

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

和这个一样,但只要你打开括号就会发现 { 你需要里面的回报。

© www.soinside.com 2019 - 2024. All rights reserved.