简体   繁体   English

重用map函数中的react组件

[英]reuse react component in a map function

I have doubt I'm doing it right when returning a component in a map iteration. 我怀疑在地图迭代中返回组件时我做对了吗。 How can I improve the code or is there any better way to do it? 我该如何改善代码或有更好的方法呢? (although my code is working) (尽管我的代码正在工作)

https://codesandbox.io/s/5yzqy6vyqx https://codesandbox.io/s/5yzqy6vyqx

Parent

function App() {
  return (
    <div className="App">
      {[
        {
          name: "banana",
          count: 3
        },
        {
          name: "apple",
          count: 5
        }
      ].map(({ name, count }) => {
        return <List name={name} count={count} />;
      })}
    </div>
  );
}

List component 清单组件

const List = ({ name, count }) => {
  return (
    <li>
      {name}: {count}
    </li>
  );
};

Simplify like this. 这样简化。

 function App() { return ( <div className="App"> <ul> {[ { name: "banana", count: 3 }, { name: "apple", count: 5 } ].map(({ name, count }) => <li>{name}:{count} </li>)} </ul> </div> ); } 

You need to set unique value as key to List component because you are rendering List in loop. 您需要将唯一值设置为List组件的键,因为您正在循环渲染List。 Unique value can be id per each object in array or index from .map but we are recommended to have unique id per object in data and use that as key when we iterate. 唯一值可以是数组中每个对象的ID,也可以是.map中索引的唯一ID,但我们建议数据中每个对象具有唯一ID,并在迭代时将其用作键。

Index is not recommended as key but in worst case we can. 不建议将索引作为关键,但在最坏的情况下我们可以。

Also add ul element so that li will be rendered under ul 同时添加ul元素,以便在ul下呈现li

Below code has improved with adding key, ul and .map function without return 下面的代码通过添加key,ul和.map函数而没有返回而得到了改进

    function App() {
         return (
              <div className="App">
                <ul>
                 {[
                    {
                       id: 1
                       name: "banana",
                       count: 3
                    },
                    {
                     id:2,
                     name: "apple",
                     count: 5
                    }
                   ].map(({ id, name, count }) => (
                     <List key={id} name={name} count={count} />;
                ))}
              </ul>
            </div>
           );
      }

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

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