简体   繁体   English

对映射数据执行条件渲染操作 - React

[英]Perform conditional render operations on mapped data - React

I am mapping data within the returned render, but I am wanting to then perform a conditional on the data that has been mapped... Is it possible to do something like this?我在返回的渲染中映射数据,但我想对已映射的数据执行条件......是否可以做这样的事情?

export default function App() {
  const prod = [
    {'name': '1'},
    {'name': '2'},
    {'name': '3'}
  ];

  return (
    <div className="App">
      {prod && (
        <div>
          {prod.map(p => (

            // This is the point I get an error
            {p.name === '1' && (
              <h1>This is 1</h1>
            )}

          ))}
        </div>
      )}
    </div>
  );
}

Currently I am getting an error:目前我收到一个错误:

Unexpected token, expected "," (16:14)

  14 |         <div>
  15 |           {prod.map(p => (
> 16 |             {p.name === '1' && (
     |               ^

Arrow functions with the format x => () return the content of the brackets.格式为x => ()的箭头函数返回括号的内容。

So you are returning what the compiler thinks is an object, as it's wrapped in curly brackets x => ({... }) You need to remove the braces:因此,您返回的是编译器认为是 object 的内容,因为它包含在大括号x => ({... })中,您需要删除大括号:

prod.map(p => (
    p.name === '1' && <h1>This is 1</h1>
)

Or explicitly return the value:或显式返回值:

prod.map(p => {
    return p.name === '1' && <h1>This is 1</h1>
}

If you want to map the data for any specific index then you can check this.如果你想 map 任何特定索引的数据,那么你可以检查这个。

<div>
    {prod.map(p => p.name === '1' && <h1>Conditionally Mapped</h1> || <h1>Normally mapped</h1>}
</div>

// similar to the previous one

<div>
    {prod.map(p => {
      if(p.name === '1') return <h1>Conditionally Mapped</h1>
      else return <h1>Normally mapped</h1>
    }

</div>



声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM