渲染时,未定义不是React本机中的对象

Getting undefined is not an object in React native when rendering

本文关键字:本机 React 对象 未定义      更新时间:2023-09-26

我是ReactReact native的新手,正在尝试retrieve data from an API,然后渲染它,但我似乎遇到了问题。

我可以从API中获取数据,但当我尝试render时,我会遇到各种错误。

从本质上讲,我所要做的就是渲染从API返回的照片。应该是简单的吧?如果有人能为我指明正确的方向,我将不胜感激。

我收到的错误如下:

未定义不是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>
    )
  }
});

对于那些在上面的答案中找不到问题解决方案的人:-

这解决了我的问题:我更改了的代码

import {React} from 'react';

import React from 'react';

实际情况是,由于默认情况下React是从模块导出的,所以我不能用大括号将其包裹起来。

您有两个问题。

首先,传递给RenderPhotos的道具是this.props.photos,它在AwesomeProject中未定义。在RenderPhotosrender()函数中,您尝试访问this.props.photos的索引0处的元素,该元素未定义。这可能就是造成你错误的原因。我怀疑您是想在AwesomeProject组件的render()函数中将照片道具设置为等于this.state.photos

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

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

React可能会批处理这两个setState()调用,但不能保证,因此这两个状态属性将同时设置,并且render()方法将只调用一次。然而,如果这些setState()函数被同步执行,则在this.state.loading === falsethis.state.photos === undefined时将调用render()函数。RenderPhotos组件将安装并接收道具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>
    )
  }
});