我正在使用来自NPM的unsplash-js api

我在我的反应项目中使用了unsplash-js,当我使用search查询获取一些随机照片时,我在下面的JSON检查中得到了返回结果。

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

results:Array(10)0:{id:“nitdfruLYys”,created_at:“2016-10-12T13:04:23-04:00”,updated_at:“2017-08-02T04:08:11-04:00” ,width:4000,height:6000,…} 1:{id:“XE87arvN3oo”,created_at:“2015-12-12T11:43:35-05:00”,updated_at:“2017-08-02T12:08:22 -04:00“,width:4272,height:2848,…} 2:{id:”iS0Aq3QPsJ4“,created_at:”2016-02-26T19:51:15-05:00“,updated_at:”2017-08- 02T16:36:55-04:00“,width:3000,height:1691,…} 3:{id:”41eXcLghVhI“,created_at:”2017-07-15T20:50:43-04:00“,updated_at: 4:{id:“EjlygRQAOik”,created_at:“2017-02-07T19:59:18-05: 00“,updated_at:”2017-08-02T00:30:17-04:00“,width:5000,height:3333,…} 5:{id:”WicMLrOSVvY“,created_at:”2015-10-24T13:40 :06-04:00“,updated_at:”2017-07-31T07:00:30-04:00“,width:3456,height:2304,…} 6:{id:”Fu8pblIzEL0“,created_at: 03-06T16:49:09-05:00“,updated_at:”2017-08-01T20:41:35-04:00“,width:4928,height:3264,…} 7:{id:”D9XX 3Cjoh2s“,created_at:”2016-02-21T15:45:25-05:00“,updated_at:”2017-08-02T20:44:56-04:00“,width:6000,height:4000,…} 8 :{id:“Aka2x2D4Ph0”,created_at:“2016-01-21T03:42:02-05:00”,updated_at:“2017-07-28T10:24:12-04:00”,width:5616,height: 3744,…} 9:{id:“E-1tnSNP0y4”,created_at:“2015-11-08T19:32:31-05:00”,updated_at:“2017-07-30T17:19:06-04:00” ,width:5472,height:3648,…} length:10 proto :Array(0)total:303 total_pages:31 proto :Object

我需要设置这个状态作为一个数组,但是当我在我的代码中设置我得到这个错误:对象是无效的作为一个React的孩子

this.setState({photos:json});

尝试使用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")); 

我需要设置这个状态作为一个数组,但是当我在我的代码中设置我得到这个错误:对象是无效的作为一个React的孩子

我认为这个问题可能与setState调用无关。 当一个对象作为一个子对象传递给一个反应组件时,会发生这个错误,并且会在下面的命令中被调用

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

PhotoList ,错误可能是由于您如何使用PhotoList组件中的照片而PhotoList 。 我会检查照片列表中的照片的使用情况,并validationthis.props.photos是不是作为一个孩子传递给一个组件。