我刚接触ReactReact native,正在try retrieve data from an API,然后渲染它,但我似乎遇到了问题.

我可以从API中获取数据,但是当我try 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>
    )
  }
});

推荐答案

你有两个问题.

首先,你传递给RenderPhotos的props 是this.props.photos,在AwesomeProject中没有定义.在RenderPhotosrender()函数中,您try 访问this.props.photos的索引0处的元素,这是未定义的.这可能就是你犯错误的原因.我猜你是想在AwesomeProject组件的render()函数中将photos prop设置为this.state.photos.

其次,在AwesomeProject组件的componentWillMount()中,从API获取照片后,您会进行两个状态更改:

this.setState({
  isLoading: false
});

this.setState({
  photos: JSON.stringify(responseData)
});

React可能会对这两个setState()次调用进行批处理,因此两个状态属性都会同时设置,render()方法只会被调用一次,这是可能的,但不能保证的.然而,如果这setState()个函数是同步执行的,则render()函数将在this.state.loading === falsethis.state.photos === undefined时被调用.RenderPhotos组件将安装并接收props photos={this.state.photos}(在进行上述更改后).不幸的是,由于this.state.photos未定义,当您试图访问RenderPhotosrender()函数中的this.props.photos[0]时,您将遇到与上述相同的问题.以下是我对解决您的问题的建议:

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)
            )
            // Set both state properties at the same time to avoid passing an undefined value as a prop to RenderPhotos
            this.setState({
              isLoading: false,
              photos: JSON.stringify(responseData)
            });
        })
        .done();
    },
    render: function() {
        if(this.state.isLoading){
          return <View><Text>Loading...</Text></View>
       }
       // RenderPhotos should receive this.state.photos as a prop, not this.props.photos
        return (
            <RenderPhotos photos={this.state.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>
    )
  }
});

React-native相关问答推荐

如何将S的此API输出输出到平面列表中?控制台将数据及其可视记录到平面列表中,但我无法输出到平面列表中

在 React Native 中,水平滚动不适用于我的整个应用程序

用图像 react native 动画进度条

如何在react-navigation 中将drawer抽屉放在标题上?

判断状态对象是否为空

使用 resizeMode 封面截断的图像

IntelliSense 在第一项后无法在 React Native 样式表中工作

React-Native:save user preferences

iPhone 6s plus 上的字体大小

如何将抖动动画添加到视图(react-native)?

在 react-native 元素中更改 android 和 ios 的入口文件路径

可以在没有 await 关键字的情况下调用异步函数吗?

从堆栈导航器中删除屏幕

textAlignVertical不是有效的样式属性

React-Native 应用程序中来自 Babel 的未知选项错误

在 React Native 中无法滚动到 ScrollView 的底部

props验证中缺少 React Navigation 'navigation'

组件div的视图配置 getter 回调必须是一个函数(收到 undefined)

查找文本输入框和按钮字段的资源名称以响应本机 android 应用程序

react-native:webview 高度