我正在尝试迭代/映射对象数组并使用嵌套值,但我似乎无法让它工作。如果我传入一个简单的数组
const people = [
{ name: "joe", id: "1" },
{ name: "mary", id: "2" }
];
到我的ShowList组件
const ShowList = (props) => {
const {people} = props;
return ( renderPeep(people))
};
const renderPeep = (people) => (
<ul>
{people.map((peep, index) => (
<li key={index}>{peep}</li>
))}
</ul>
)
我得到两个值的列表:
joe1
mary1
并且点符号和括号都不起作用({peep.name}
)只列出名称。是map函数导致我们丢失底层对象的密钥信息?我错过了什么?
答案 0 :(得分:1)
将<li key={index}>{peep}</li>
更改为<li key={index}>{peep.name}</li>
。在array#map
内您获得了一个对象,您可以使用点表示法或括号表示法访问name
。
或者,您也可以使用解构:
const renderPeep = (people) => (
<ul>
{people.map(({name}, index) => (
<li key={index}>{name}</li>
))}
</ul>
)
const people = [
{ name: "joe", id: "1" },
{ name: "mary", id: "2" }
];
const ShowList = (props) => {
const {people} = props;
return (renderPeep(people));
};
const renderPeep = (people) => (
<ul>
{people.map((peep, index) => (
<li key={index}>{peep.name}</li>
))}
</ul>
)
ReactDOM.render(
<ShowList people={people} />,
document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'></div>