2017-02-25 159 views
0

我通过道具发送数组通过道具,但我不能使用阵列上的地图。它说,不能使用通过道具发送的数组

.MAP不是一个函数

我的代码:

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的开发做出反应工具的样子:

enter image description here

回答

2

问题是,当你从父母和孩子之间传递的任何数据,它打通道具过去了,你需要接受的子组件的道具和访问的具体数值,它这样写:

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

之所以第二届一个工作:因为道具是一个对象,当你写{authors}这意味着您只收到对象propsauthors值。在这种情况下,你不需要写props.authors

检查这个例子:

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

+0

非常感谢!我知道为什么它不工作,这是失去{},只从道具提取作者。谢谢! –

1

道具将作为一个对象传入,所以现在authors正在作为props的别名。在props上访问authors属性应该只要该prop正在使用数组声明。

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

奇怪的是,我在我的应用程序的其他部分相同的图形,并且其工作,是什么使这个代码工作的区别? const CourseList =({courses})=> {.......... {courses.map(course => )} –

+1

围绕'courses'的曲线是[object destructure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)。从'props'中拉出'courses',相当于使用'props.courses'而没有解构。从上面的'AuthorList'代码中缺少这个。 – max