从数组中渲染数据
-
渲染以下数据
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渲染列表的几种方法
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
喜欢就支持一下吧
相关推荐
暂无评论内容