繁体   English   中英

反应 js 迭代组件道具中的数组

[英]react js iterate over array in Component props

我有一个需要传递数据的组件,在数组中搜索。 数组存储在变量中,数据需要去组件属性。 考虑以下;

const users = [
   {"id": 1, "username": 'name1'},
   {"id": 2, "username": 'name2'},
   {"id": 3, "username": 'name3'},
   {"id": 4, "username": 'name4'},
   {"id": 5, "username": 'name5'}
]

const listItemData = [1,2,3];

<List
    size="small"
    bordered
    dataSource={listItemData}
    renderItem={item => <List.Item>{item}</List.Item>}//need name1, name2, name3 but get 1,2,3 here
/>

所以在这里我有一个用户数组,其中存储了有关所有用户的所有数据,以及我只有 id 的特定列表项数组。 出于渲染目的,我需要渲染用户名而不是 id。 据我所知,我可以遍历组件renderItem用户 ID,并显示与其 ID 与listItemData中的 ID 匹配的用户用户username

任何想法如何做到这一点将受到欢迎。 谢谢

const users = [
  {"id": 1, "username": 'name1'},
  {"id": 2, "username": 'name2'},
  {"id": 3, "username": 'name3'},
  {"id": 4, "username": 'name4'},
  {"id": 5, "username": 'name5'}
];

const ids = [1,2,3];

const listItems = users.reduce((a, c) => {
  a[c.id] = c.username;
  return a;
}, {});

<List
  size="small"
  bordered
  dataSource={ids}
  renderItem={id => <List.Item>{listItems[id]}</List.Item>}
/>
import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { List, Avatar } from 'antd';

const users = [
  {"id": 1, "username": 'name1'},
  {"id": 2, "username": 'name2'},
  {"id": 3, "username": 'name3'},
  {"id": 4, "username": 'name4'},
  {"id": 5, "username": 'name5'}
]

const listItemData = [1,2,3];


const data = users.filter((user)=>listItemData.includes(user.id))
ReactDOM.render(
  <List
    itemLayout="horizontal"
    dataSource={data}
    renderItem={item => (
      <List.Item>
        <List.Item.Meta          
          title={<a href="https://ant.design">{item.username}</a>}          
        />
      </List.Item>
    )}
  />,
  document.getElementById('container'),
);

您需要过滤掉这些值,然后将其设置为新的数据源。 顺便说一下,在您的代码中,您使用了错误的数据源。 首先过滤掉匹配的数据,然后它就像一个魅力!!!

暂无
暂无

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

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