简体   繁体   English

TypeError:无法使用React读取undefined的属性

[英]TypeError: Cannot read property of undefined using React

I'm new in React and I'm doing a little app with PokeAPI. 我是React的新手,并且正在使用PokeAPI做一个小应用程序。 I have a component called PokemonDetail in which I want to show the details of a pokemon, but the app throws me the next error 我有一个名为PokemonDetail的组件,我想在其中显示一个神奇宝贝的详细信息,但是应用程序抛出了下一个错误

TypeError: Cannot read property 'front_default' of undefined TypeError:无法读取未定义的属性“ front_default”

my component looks like this: 我的组件看起来像这样:

import React from "react";

const PokemonDetail = ({ pokemon }) => {
  return (
    <div>
      <div className="text-center">{pokemon.name}</div>
      <img src={pokemon.sprites.front_default} alt={pokemon.name} />
      {pokemon.id}
    </div>
  );
};

export default PokemonDetail;

And the App component from which the PokemonDetail recive the prop of pokemon looks like this: PokemonDetail从中获取Pokemon道具的App组件如下所示:

import React from "react";
import PokeAPI from "../apis/PokeAPI";
import SearchBar from "./SearchBar";
import PokemonDetail from "./PokemonDetail";

class App extends React.Component {
  state = { pokemon: '' };

  onTermSubmit = async term => {
    try {
      const response = await PokeAPI.get(`pokemon/${term}`);
      this.setState({ pokemon: response.data });
      console.log(response);
    } catch (error) {
      console.log("No existe");
    }
  };

  render() {
    return (
      <div className="container">
        <div className="row mt-3">
          <div className="col">
            <SearchBar onFormSubmit={this.onTermSubmit} />
          </div>
        </div>
        <div className="row mt-3">
          <div className="col-9" />
          <div className="col-3">
            <PokemonDetail pokemon={this.state.pokemon} />
          </div>
        </div>
      </div>
    );
  }
}

export default App;

I don't understand why it throws me this error because only throws it with this and other properties of the json. 我不明白为什么它会引发此错误,因为仅将其与json的此属性和其他属性一起引发。 With the name property works and wait until I send it some props, same with the id but no with the front_default property, which is a url of a image. 有了name属性,然后等待直到我发送一些道具,这些道具与id相同,但与front_default属性(即图像的网址)相同。

Because ajax is slower than react rendering, you can use a loading component before you get the data. 因为ajax比反应渲染慢,所以可以在获取数据之前使用加载组件。

 const PokemonDetail = ({ pokemon }) => { if(pokemon.sprites == undefined){ return( <div> Loading... </div> ); } return ( <div> <div className="text-center">{pokemon.name}</div> <img src={pokemon.sprites.front_default} alt={pokemon.name} /> {pokemon.id} </div> ); }; 

Very likely just an AJAX issue, your component renders before it has time to complete your request to the API. 很可能只是AJAX问题,您的组件会在有时间完成对API的请求之前呈现。 Try adding an additional check before rendering the image. 渲染图像之前,请尝试添加其他检查。

import React from "react";

const PokemonDetail = ({ pokemon }) => {
  return (
    <div>
      <div className="text-center">{pokemon.name}</div>
       {pokemon.sprites ? (
        <img src={pokemon.sprites.front_default} alt={pokemon.name} />
        ) : ( 
          null
        )
       }
      {pokemon.id}
    </div>
  );
};

export default PokemonDetail;

@ZHAOXIANLONG gave you the best solution (use a loading component until you receive data), but, if you do not use a loading component, you can use the get method from lodash library [1] in order to avoid a possible error. @ZHAOXIANLONG为您提供了最佳解决方案(在接收数据之前使用加载组件),但是,如果不使用加载组件,则可以使用lodash库[1]中的get方法以避免可能的错误。

import React from "react";
import _ from 'lodash';

const PokemonDetail = ({ pokemon }) => {
    const front_default = _.get(pokemon, 'sprites.front_default', 'DEFAULT_VALUE');
    const name = _.get(pokemon, 'name', 'DEFAULT_VALUE');

    return (
        <div>
            <div className="text-center">{pokemon.name}</div>
            <img src={pokemon.sprites.front_default} alt={pokemon.name} />
            {pokemon.id}
        </div>
    );
};

export default PokemonDetail;

where the third parameter ('DEFAULT_VALUE') is a default value that will be used if the lodash can not retrieve a value for your query. 其中第三个参数('DEFAULT_VALUE')是默认值,如果lodash无法为您的查询检索值,将使用该默认值。

PS: I advise you to use lodash even in @ZHAOXIANLONG solution if you know that your API Server can be changed. PS:如果您知道可以更改API服务器,我建议您甚至在@ZHAOXIANLONG解决方案中使用lodash。

[1] https://lodash.com/docs/4.17.11#get [1] https://lodash.com/docs/4.17.11#get

The initial state is { pokemon: '' } ; 初始状态为{ pokemon: '' } pokemon is an empty string. pokemon是一个空字符串。 PokemonDetail is referring to pokemon.sprites.front_default , but pokemon is initially a string and a string does not have a field called sprites . PokemonDetail引用的是pokemon.sprites.front_default ,但是pokemon最初是一个字符串,并且字符串没有名为sprites的字段。

If you are expecting pokemon to eventually become an object, you could initialize it to something that looks like an object: 如果期望口袋妖怪最终成为对象,则可以将其初始化为看起来像对象的东西:

state = { pokemon: { sprites: {front_default: '' }}};

暂无
暂无

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

相关问题 使用React的新功能:TypeError:无法读取未定义的属性“ map” - New using React: TypeError: Cannot read property 'map' of undefined TypeError:无法读取undefined的属性'firstName' - 在react中使用'props' - TypeError: Cannot read property 'firstName' of undefined - using 'props' in react 使用React时的TypeError:无法读取未定义的属性“firstChild” - TypeError when using React: Cannot read property 'firstChild' of undefined TypeError:使用“窗口”时无法读取未定义反应错误的属性“位置” - TypeError: Cannot read property 'location' of undefined react error on using 'window' React - 未捕获的类型错误:无法使用 Airtable 读取未定义的属性“名称” - React - Uncaught TypeError: Cannot read property "name' of undefined using Airtable TypeError:无法使用 REDUX 读取 REACT 中未定义的属性“映射” - TypeError: Cannot read property 'map' of undefined in REACT using REDUX 类型错误:无法读取 React 中未定义的属性“map” - TypeError: Cannot read property 'map' of undefined in React 反应-未捕获的TypeError:无法读取未定义的属性“ 1” - React - Uncaught TypeError: Cannot read property '1' of undefined React Express TypeError:无法读取未定义的属性“ then” - React Express TypeError: Cannot read property 'then' of undefined 类型错误:无法读取未定义 React 的属性“任何” - TypeError: Cannot read property 'any' of undefined React
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM