2017-10-19 74 views
0
import React, { Component } from 'react'; 

class newsList extends React.Component { 

    render(){ 

     return(
      <div> 
       {JSON.stringify(this.props.arr)} 
      </div> 
     ) 
    } 

} 

export default newsList; 

在上面的代碼中,arr是來自另一個組件的對象。我可以使用JSON.stringify(this.props.arr.result)來顯示數據。但只要我將其更改爲JSON.stringify(this.props.arr.result.id),就會收到錯誤消息0123'。我無法理解我在這裏做錯了什麼?如何訪問反應組件中的道具?

+0

你能提供一個'props'的樣子嗎? –

+0

,因爲它對你的'arr'對象有問題,所以最好顯示數據。 – wakwak

+0

更有可能的是,你的'this.props.arr'在你的代碼中的某個時候是'undefined'。 – Andrew

回答

0

this.props.arr數組? 如果是這樣,渲染功能應該是

render(){ 
    var ids = this.props.arr.map(e=>(<div>e.result.id</div>)) 
    return(
     <div> 
      {ids} 
     </div> 
    ) 
} 
+0

是的。它是一組對象。 – Parth

+0

@Parth我認爲它會工作 – RalfZ

0

嘗試這個代碼,而不是:

class NewsList extends React.Component { 
    constructor(props) { 
     super(props); 
     this.props = props; 
    } 
    render() { 
     return <div>{this.props.arr}</div>; 
    } 
} 

一個React.Componentconstructor總是收到props,因爲它是第一個參數。

+0

使用'super(道具)'是最普遍的用法。無論如何,這不是問題。您可以在React組件中接受道具而不明確指出'構造函數' – Andrew

+0

當我使用'this.props = props'時,我收到一個錯誤。錯誤說「這在super()'之前是不允許的。 – Parth

+0

啊,是的。將您的代碼更改爲上面的編輯。 –

1

我幾乎肯定在某個時間點,您的this.props.arrundefined,但最終會得到一個值。您的初始渲染將收到nullundefined,但如果您嘗試向更遠的一個鍵不存在,則會拋出該錯誤。您可以使用布爾值來控制最初呈現的內容。

代替此行代碼:

{JSON.stringify(this.props.arr)} 

試試這個:

{this.props.arr ? JSON.stringify(this.props.arr) : null} 

編輯:是this.props.arr.result.id您的問題?如果是這樣,請使用此代替

{this.props.arr.result ? JSON.stringify(this.props.arr.result.id) : null} 
+0

它正在工作。非常感謝@Andrew。 – Parth

+0

@Parth總是樂於幫忙。如果你不介意,請標記這是正確的答案:) – Andrew

相關問題