从数组中渲染数据
-
渲染以下数据
const people = [{
id: 0,
name: 'Creola Katherine Johnson',
profession: 'mathematician',
}, {
id: 1,
name: 'Mario José Molina-Pasquel Henríquez',
profession: 'chemist',
}, {
id: 2,
name: 'Mohammad Abdus Salam',
profession: 'physicist',
}, {
name: 'Percy Lavon Julian',
profession: 'chemist',
}, {
name: 'Subrahmanyan Chandrasekhar',
profession: 'astrophysicist',
}];
-
用 map
来渲染数据
//App.js
function List({people}) {
console.log('people',people)
const listItems = people.map(
person=> <li key={person.id}>{person.name}:{person.profession} </li>
)
return <ul>{listItems}</ul>
}
export default function App() {
const people = [{
id: 0,
name: 'Creola Katherine Johnson',
profession: 'mathematician',
}, {
id: 1,
name: 'Mario José Molina-Pasquel Henríquez',
profession: 'chemist',
}, {
id: 2,
name: 'Mohammad Abdus Salam',
profession: 'physicist',
}, {
id: 3,
name: 'Percy Lavon Julian',
profession: 'chemist',
}, {
id:4,
name: 'Subrahmanyan Chandrasekhar',
profession: 'astrophysicist',
}];
return (
<List people={people}></List>
);
}
以上代码,我们在父组件中将数据传递给子组件,子组件接受数据并且渲染。
注意:在map
渲染中一定要填上我们的key
-
使用 filter()
如果你只想显示职业为chemist的人,可以调用filter()
方法
//定义一个List组件
function List({people}) {
const chemists = people.filter(person =>
person.profession === 'chemist'
);
const listItems = chemists.map(
person=> <li key={person.id}>{person.name}:{person.profession} </li>
)
return <ul>{listItems}</ul>
}
export default function App() {
const people = [{
id: 0,
name: 'Creola Katherine Johnson',
profession: 'mathematician',
}, {
id: 1,
name: 'Mario José Molina-Pasquel Henríquez',
profession: 'chemist',
}, {
id: 2,
name: 'Mohammad Abdus Salam',
profession: 'physicist',
}, {
id: 3,
name: 'Percy Lavon Julian',
profession: 'chemist',
}, {
id:4,
name: 'Subrahmanyan Chandrasekhar',
profession: 'astrophysicist',
}];
return (
<List people={people}></List>
);
}
原文始发于微信公众号(大前端编程教学):React渲染列表的几种方法
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/224170.html