2017-08-03 21 views
1

我在我的反應項目中使用unsplash-js,當我使用搜索查詢獲取一些隨機照片時,我在下面的JSON檢查形式獲取返回。我正在使用從NPM的unsplash-js api與反應

{total: 303, total_pages: 31, results: Array(10)} 

結果 : 陣列(10): {ID: 「nitdfruLYys」,created_at: 「2016-10-12T13:04:23-04:00」,的updated_at:「2017年-08-02T04:08:11-04:00「,width:4000,height:6000,...} : {id:」XE87arvN3oo「,created_at:」2015-12-12T11:43:35-05 :00「,updated_at:」2017-08-02T12:08:22-04:00「,width:4272,height:2848,...} : {id:」iS0Aq3QPsJ4「,created_at:」2016-02 -26T19:51:15-05:00「,updated_at:」2017-08-02T16:36:55-04:00「 ,width:3000,height:1691,...} : {id:「41eXcLghVhI」,created_at:「2017-07-15T20:50:43-04:00」,updated_at:「2017-08-02T14: 31:32-04:00「,width:4608,height:3072,...} : {id:」EjlygRQAOik「,created_at:」2017-02-07T19:59:18-05:00「,updated_at :「2017-08-02T00:30:17-04:00」,width:5000,height:3333,...} : {id:「WicMLrOSVvY」,created_at:「2015-10-24T13: 06-04:00「,updated_at:」2017-07-31T07:00:30-04:00「,width:3456,height:2304,...} : {id:」Fu8pblIzEL0「,created_at:」 2015-03-06T16:49:09-05:00「,updated_at:」2017-08-01T20:41:35-04:00「,width:4928,height:3264,...} : {id:「D9XX3Cjoh2s」,created_at:「2016-02-21T15:45:25-05:00」,updated_at:「2017-08-02T20:44:56-04:00」,width: 6000,height:4000,...} : {id:「Aka2x2D4Ph0」,created_at:「2016-01-21T03:42:02-05:00」,updated_at:「2017-07-28T10:24:12 -04:00「,width:5616,height:3744,...} : {id:」E-1tnSNP0y4「,created_at:」2015-11-08T19:32:31-05:00「,updated_at: 「2017-07-30T17:19:06-04:00」,寬度:5472,高度:3648,...} 長度 : : 陣列(0) 總 : TOTAL_PAGES : : 對象

我需要設置的狀態爲一個數組,但是當我在我的代碼我收到此錯誤設置如下:對象作爲React子項無效

this.setState({photos:json});

+0

你能發表你的相關反應代碼片段嗎 –

+0

https://jsfiddle.net/9bhccn1y/ –

回答

0

嘗試重構使用componentDidMount生命週期方法的代碼。

class App extends React.Component { 
    constructor(props) { 
     super(props); 

     this.state = { photos: [] }; 
    } 

    componentDidMount() { 
     // make API calls here 

     this.setState({ photos }); 
    } 

    render() { 
     return (
      <div> 
       <SearchBar /> 
       <PhotoList photos={this.state.photos} /> 
      </div> 
     ); 
    } 
} 

ReactDOM.render(<App />, document.getElementById("root")); 

I need to set this in a state as an array, but while i am setting this in my code i am getting this error: Objects are not valid as a React child

我覺得這是問題可能是無關的setState通話。當一個對象被傳遞給反應組件作爲一個孩子,下面cicumstance

render() { 
    const sample = { 
     a: 5, 
     b: 6, 
     c: 7 
    } 
    return (
     <div> 
      {sample} 
     </div> 
    ) 
} 

這是說,這個錯誤可能發生下會被稱爲發生是由於您如何使用中的照片此錯誤PhotoList組件。我會檢查PhotoList中照片的使用情況,並確認this.props.photos未被作爲孩子傳遞給組件。

+0

使用你的方法,但仍然顯示錯誤 - 對象作爲一個React孩子無效(發現:對象與鍵{ id),created_at,updated_at,width,height,color,likes,likes_by_user,description,user,current_user_collections,url,categories,links}) –

+0

'code' componentDidMount(){ //在此處調用API調用 unsplash.search。照片(「狗」,1) 。然後(toJson) 。然後(json => { //console.log(json.results); this.setState({photos:json.results}) }) ; } –

+0

查看修改內容 –