2017-02-25 15 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