我是React
和React native
的新手,我正在尝试retrieve data from an API
然后渲染它,但我似乎遇到了问题。
我可以从API
获取数据,但是当我尝试render
时,我会收到各种各样的错误。
基本上我尝试做的就是渲染从API返回的照片。应该简单吧?非常感谢能够指引我走上正轨的人。
我收到的错误如下:
undefined不是RenderPhotos_render中的对象(评估' this.props.photos')
我可能过早地跳入React Native
...原谅我缺乏知识!
var AwesomeProject = React.createClass({
getInitialState: function() {
return {
isLoading: true,
photos: this.props.photos
};
},
componentWillMount: function(){
fetch("http://localhost:3000/api/photos/", {
method: "GET",
headers: {
"x-access-token":"xxxxx",
"x-key":"xxxx"
},
})
.then((response) => response.json())
.then((responseData) => {
AlertIOS.alert(
"GET Response",
"Search Query -> " + JSON.stringify(responseData)
)
this.setState({
isLoading: false
});
this.setState({
photos: JSON.stringify(responseData)
});
})
.done();
},
render: function() {
if(this.state.isLoading){
return <View><Text>Loading...</Text></View>
}
return (
<RenderPhotos photos={this.props.photos}/>
);
},
});
var RenderPhotos = React.createClass({
getInitialState: function() {
return {
photos: this.props.photos
};
},
render: function(){
var photos = Photos;
return (
<View>
<Text> {this.props.photos[0]} </Text>
</View>
)
}
});
答案 0 :(得分:5)
你有两个问题。
首先,您传递给RenderPhotos
的道具是this.props.photos
,AwesomeProject
中未定义。查看render()
的{{1}}函数,您尝试访问RenderPhotos
的索引0处的元素,该元素未定义。这可能是导致你的错误的原因。我怀疑你打算在this.props.photos
组件的this.state.photos
函数中将照片道具设置为render()
。
其次,在AwesomeProject
组件的componentWillMount()
内,您在从API获取照片后进行了两次状态更改:
AwesomeProject
React可以批量处理这两个this.setState({
isLoading: false
});
this.setState({
photos: JSON.stringify(responseData)
});
调用,但不能保证,因此两个状态属性将同时设置,setState()
方法只调用一次。但是,如果同步执行这些render()
函数,则会在setState()
和render()
时调用this.state.loading === false
函数。 this.state.photos === undefined
组件将挂载并接收道具RenderPhotos
(在进行上述更改后)。很遗憾,由于photos={this.state.photos}
未定义,因此当您尝试访问this.state.photos
this.props.photos[0]
函数内的render()
时,会遇到与上述相同的问题。以下是我解决问题的建议:
RenderPhotos
答案 1 :(得分:1)
对于以上答案中未找到解决问题的人:-
这解决了我的问题: 我从
更改了代码import {React} from 'react';
到
import React from 'react';