简体   繁体   English

无法使用通过道具发送的数组

[英]Not being able to use an array sent in via props

Im sending in an array via props to a component, but i cant use map on the array. 我通过道具发送数组到组件,但是我不能在数组上使用map。 It says that 它说

.map is not a function .map不是函数

My code: 我的代码:

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>
);
};

This is what the Chrome React dev tool looks like: Chrome React开发工具如下所示:

在此处输入图片说明

Issue is, whenever you pass any data from parent to child, it get passed through props, and you need to receive the props in child component and access the specific values, write it like this: 问题是,每当您将任何数据从父级传递到子级时,它都会通过prop传递,并且您需要在子组件中接收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>
);
};

or 要么

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>
    );
};

Reason why 2nd one is working : because props is an object, when you write {authors} it means you are receiving only authors value from object props . 第二个代码起作用的原因 :因为props是一个对象,所以当您编写{authors} ,意味着您仅从对象props接收authors值。 In that case you don't need to write props.authors . 在这种情况下,您无需编写props.authors

Check this example: 检查以下示例:

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

Props will be passed in as an object, so right now authors is acting as an alias for props . 道具将作为对象传递,因此现在authors正在充当props的别名。 Accessing the authors property on props should work as long as that prop is being declared with an array. 只要使用数组声明道具,就可以访问propsauthors属性。

const AuthorList = (props) => {
  return(
     // ..
            {props.authors.map(author => 
                <AuthorListRow key={author.id} author={author} />
            )}
     // ..
 );
};

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

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