开发者问题收集

为什么我得到 TypeError: 无法读取未定义的属性“toLowerCase”

2019-03-22
16077

我正在建立一个名为 starwarplanet 的网站。

它使用 react.js 来构建。

它使用的 api 是 这个网站

我从中得到的错误是

TypeError: Cannot read property 'toLowerCase' of undefined

我只想显示行星的 名称直径旋转周期

我的 app.jscard.js 中有什么问题?

app.js 中:

import React,{Component} from 'react';
import CardList from '../Components/CardList';
import SearchBox from '../Components/SearchBox';
import Scroll from '../Components/Scroll';
import './App.css';

class App extends Component{
    constructor(){
        super()
        this.state={
            planets:[],
            searchfield:''
        }
     }
     componentDidMount() {
        const urls = [
           'https://swapi.co/api/planets/',
           'https://swapi.co/api/planets/?page=2', 
           'https://swapi.co/api/planets/?page=3',
           'https://swapi.co/api/planets/?page=4',
           'https://swapi.co/api/planets/?page=5',
           'https://swapi.co/api/planets/?page=6',
           'https://swapi.co/api/planets/?page=7'
    ]
    
    Promise.all(urls.map(async url => {
        const response = await fetch(url);
        const morePlanets = await response.json();
        var combinedArrayOfPlanets = this.state.planets;
        combinedArrayOfPlanets.push(morePlanets.results);
        
        var sortedArrayOfPlanets = combinedArrayOfPlanets
            .flat()
            .sort((a, b) => a.name.localeCompare(b.name));
        
        this.setState({planets: sortedArrayOfPlanets})
    }))
    .catch(error => 
        console.log('Error during fetching of planets:', error)
    );
}

onSearchChange = (event) => {
    this.setState({ searchField: event.target.value })
}
render(){
    const {planets,searchField} = this.state;
    const filteredPlanets = planets.filter(planet=>{
        return planet.name.toLowerCase().includes(
            searchField.toLowerCase())
            ||
            planet.diameter.toLowerCase().includes(
                searchField.toLowerCase())
            ||
            planet.rotation_period.toLowerCase().includes(
                searchField.toLowerCase())
    })
    return !planets.length?
    (
        <div className='tc'>
                    <h1>Loading</h1>:
        </div>
    ):
    (
    <div className='tc'>
        <h1 className='f2'>StarWarPlanet</h1>
        <SearchBox searchChange={this.onSearchChange}/>
        <Scroll>
            <CardList planets = {filteredPlanets}/>
        </Scroll>
    </div>
    );
   }
  }

 export default (App);

Card.js 中:

import React from 'react';

const Card = ({name,diameter,rotation_period}) =>{
    return(
       <div className="bg-light-green dib br3 pa3 ma2 grow bw2 shadow-5">
            <div>
                <h2>{name}</h2>
                <p>{diameter}</p>
                <p>{rotation_period}</p>
            </div>
       </div>
    );
   }

   export default Card;
3个回答

当您想要对不存在的事物执行操作时,就会出现错误。您似乎正在对其父级中不存在的某些属性运行 toLowerCase 。检查错误日志以获取确切的行号。您将了解您尝试访问哪个不存在的属性。

它应该是以下之一:

planet.name.toLowerCase()
planet.diameter.toLowerCase()
planet.rotation_period.toLowerCase()

因此,请检查以确保 planet 具有所有 3 个属性: namediameterrotation_period 。如果是,请确保您使用了正确的拼写。

Manu
2019-03-22

这可能是由于数据的字符串格式不完美。尝试添加 .toString() ,然后尝试添加 .toLowerCase()

Maneesh
2019-03-22

您的组件正在尝试在数据提取完成之前进行渲染。您的代码中已进行检查,但您需要在处理任何数据之前将其移动:

render() {
    const {planets,searchField} = this.state;

    if (!planets.length) {
        return <div className='tc'><h1>Loading</h1></div>;
    }

    const filteredPlanets = planets.filter(planet=>{
        return planet.name.toLowerCase().includes(
            searchField.toLowerCase())
            ||
            planet.diameter.toLowerCase().includes(
                searchField.toLowerCase())
            ||
            planet.rotation_period.toLowerCase().includes(
                searchField.toLowerCase())
    })
    return (
        <div className='tc'>
            <h1 className='f2'>StarWarPlanet</h1>
            <SearchBox searchChange={this.onSearchChange}/>
            <Scroll>
                <CardList planets = {filteredPlanets}/>
            </Scroll>
        </div>
    );
}
miyu
2019-03-22