简体   繁体   English

渲染时获取 undefined 不是 React native 中的对象

[英]Getting undefined is not an object in React native when rendering

I'm new to React and React native and am trying to retrieve data from an API and then render it but I seem to be running into problems.我是ReactReact native新手,正在尝试retrieve data from an API然后呈现它,但我似乎遇到了问题。

I can grab the data from the API alright, but when I try and render it I'm getting all sorts of errors.我可以从API中获取数据,但是当我尝试render它时,我遇到了各种各样的错误。

Essentially all I'm trying to do is render the photos that are returned from the API.基本上我要做的就是渲染从 API 返回的照片。 Should be simple right?应该很简单吧? Would appreciate anyone who can point me in the right track.如果有人能指出我正确的方向,我将不胜感激。

I'm getting errors like:我收到如下错误:

undefined is not an object (evaluating 'this.props.photos') in RenderPhotos_render undefined 不是 RenderPhotos_render 中的对象(评估“this.props.photos”)

I may have jumped into React Native too early...So excuse my lack of knowledge!我可能太早进入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>
    )
  }
});

for those who dont find solution to their problems in answers above:-对于那些在上面的答案中找不到解决问题的方法的人:-

This solved my problem: I changed code from这解决了我的问题:我更改了代码

import {React} from 'react';

to

import React from 'react';

What happened is, since React is exported by default from the module so I cannot wrap it with curly-braces.发生的事情是,由于默认情况下React是从模块中导出的,所以我不能用大括号将它包裹起来。

You have two problems.你有两个问题。

First, the prop you pass to RenderPhotos is this.props.photos , which is undefined in AwesomeProject .首先,你传递给RenderPhotos的道具是this.props.photos ,它在AwesomeProject中是未定义的。 Looking in the render() function of RenderPhotos , you try to access the element at index 0 of this.props.photos , which is undefined.查看RenderPhotosrender()函数,您尝试访问this.props.photos的索引 0 处的元素,该元素未定义。 That's probably what's causing your error.这可能是导致您错误的原因。 I suspect you meant to set the photos prop equal to this.state.photos in the render() function of the AwesomeProject component.我怀疑您打算在this.state.photos组件的render()函数中将 photos 道具设置为等于AwesomeProject

Second, inside componentWillMount() of the AwesomeProject component, you make two state changes after you get photos from the API:其次,在AwesomeProject组件的componentWillMount()内部,在从 API 获取照片后进行两个状态更改:

this.setState({
  isLoading: false
});

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

It's possible, but not guaranteed, that React might batch those two setState() calls, so both state properties would be set at the same time and the render() method would be called only once.有可能,但不能保证,React 可能会批处理这两个setState()调用,因此两个状态属性将同时设置,并且render()方法只会被调用一次。 However, if these setState() functions are executed synchronously, the render() function will be called while this.state.loading === false and this.state.photos === undefined .但是,如果这些setState()函数是同步执行的,则render()函数将在this.state.loading === falsethis.state.photos === undefined时被调用。 The RenderPhotos component will mount and receive the prop photos={this.state.photos} (after making the change I described above). RenderPhotos组件将安装并接收道具photos={this.state.photos} (在进行上述更改之后)。 Unfortunately, because this.state.photos is undefined, you will encounter the same problem as above when you try to access this.props.photos[0] inside the render() function of RenderPhotos .不幸的是,因为this.state.photos是未定义的,当您尝试在 RenderPhotos 的render()函数中访问RenderPhotos this.props.photos[0]时,您会遇到与上述相同的问题。 Here's my suggestion to fix your problem:这是我解决问题的建议:

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>
    )
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React Native - 从 api 渲染数据时“未定义不是对象” - React Native - 'undefined is not an object' when rendering data from api 在 React Native 中获取“undefined is not and object” - Getting “undefined is not and object” in React Native 在React Native中使用子字符串时出现错误``未定义不是对象&#39;&#39; - Getting error 'undefined is not an object' when using substring with React Native React Native:“未定义不是对象”使用ListView和外部dataSource渲染组件 - React Native: “undefined is not an object” Rendering components with ListView and external dataSource 重新渲染组件时,React Native ref未定义 - React Native ref is undefined when re-rendering a component 在响应本机中承诺firebase.auth()。signOut()时,还有其他人得到未定义的对象吗? - Anyone else getting an undefined object when promising firebase.auth().signOut() in react native? 在 React Native 导航中调用导航道具方法时获取“未定义不是对象” - Getting 'undefined is not an object' when calling navigation prop methods in react native navigation 反应原生 - '未定义不是对象'? - React native - 'undefined is not an object'? 未定义不是对象反应本机 - undefined is not an object react native React Native - 未定义不是 object - React Native - Undefined is not an object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM