gpt4 book ai didi

javascript - 无法使用通过 props 发送的数组

转载 作者:行者123 更新时间:2023-11-28 18:06:29 24 4
gpt4 key购买 nike

我通过 props 向组件发送数组,但我无法在数组上使用映射。它说的是

.map is not a function

我的代码:

const AuthorList = (authors) => {
return(
<table className="table">
<thead>
<tr>Firstname</tr>
<tr>Lastname</tr>
</thead>
<tbody>
{authors.map(author =>
<AuthorListRow key={author.id} author={author} />
)}
</tbody>
</table>
);
};

这就是 Chrome React 开发工具的样子:

enter image description here

最佳答案

问题是,每当你将任何数据从父组件传递给子组件时,它都会通过 props 传递,并且你需要在子组件中接收 props 并访问特定值,这样写:

const AuthorList = (props) => {
return(
<table className="table">
<thead>
<tr>Firstname</tr>
<tr>Lastname</tr>
</thead>
<tbody>
{props.authors.map(author =>
<AuthorListRow key={author.id} author={author} />
)}
</tbody>
</table>
);
};

const AuthorList = ({authors}) => {
return(
<table className="table">
<thead>
<tr>Firstname</tr>
<tr>Lastname</tr>
</thead>
<tbody>
{authors.map(author =>
<AuthorListRow key={author.id} author={author} />
)}
</tbody>
</table>
);
};

第二个有效的原因:因为 props 是一个对象,所以当您编写 {authors} 时,意味着您只接收 authors来自对象 props 的值。在这种情况下,您不需要编写 props.authors

检查这个例子:

obj = {a:1,b:2,c:3}
let {a} = obj;
console.log(a);

关于javascript - 无法使用通过 props 发送的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42457705/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com