在渲染时,获取未定义不是React native中的对象

时间:2015-12-27 06:30:09

标签: javascript reactjs react-native

我是ReactReact 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>
    )
  }
});

2 个答案:

答案 0 :(得分:5)

你有两个问题。

首先,您传递给RenderPhotos的道具是this.props.photosAwesomeProject中未定义。查看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';