3

所以我试图使用 homeworld id 获取我的 SWAPI json-server 两次以获取 homeworld 名称,但我只是得到“TypeError:无法读取未定义的属性'name'”。我对 React 相当陌生,所以如果它看起来很乱,我很抱歉!提前致谢!

import React, { Component } from 'react';
import './Card.css';

const person = personID =>
 `http://localhost:3008/people/${personID}`

const picture = pictureID =>
 `http://localhost:3008/${pictureID}`

 // const planet = planetID =>
 //  `http://localhost:3008/planets/${planetID}`

class Card extends Component {
  constructor(props){
    super(props);
    this.state ={
      requestFailed: false,
      person: 1,
      planet: 4
    }
  }
  componentDidMount(){
    fetch(person(this.state.person))
    .then(response => {
      if(!response.ok) {
        throw Error("Network Request Failed");
      }
      return response
    })
      .then(d => d.json())
      .then(d => {
        this.setState({
          cardData: d
        })
      }, () => {
        this.setState({
          requestFailed: true
        })
      })

fetch(`http://localhost:3008/planets/${this.state.cardData.homeworld}`)
      .then(data => data.json())
      .then(data => {
        this.setState({
          homeData: data
        })
      })
  }

  render() {
    if(this.state.requestFailed === true) return <p>Error please try 
again!</p>
    if(!this.state.cardData) return <p>Loading ...</p>
    return (
      <div className='card'>
        <div className='card-content'>
            <div className='card-name'>{this.state.cardData.name}</div>
             <img src={picture(this.state.cardData.image)} 
alt='profile'/>
            <p>
            <span>Birthday:</span>
            <span>{this.state.cardData.birth_year}</span>
        </p>
        <p>
            {/* Note that in order to get the homeworld's name, you have to get the planet name from a different endpoint than the people */}
            <span>Homeworld:</span>
            <span>{this.state.homeData.name}</span>
        </p>
     </div>
   </div>

   );
  }
}


export default Card;
4

1 回答 1

4

看起来第一个问题是您尝试homeData.name在加载之前进行渲染。您可能应该进行类似于加载检查的cardData加载检查。或者你可以在加载之前什么都不渲染:

{this.state.homeData ?
  <span>{this.state.homeData.name}</span> :
  <span>Loading...</span>
}

第二个问题是您正在与第一个同时进行第二fetch个。所以这一行:homeDatafetch

fetch(`http://localhost:3008/planets/${this.state.cardData.homeworld}`)

总是会失败,因为cardData它在运行时还没有加载到状态中。

你应该做的是将它移到第一个请求的响应部分中:

fetch(person(this.state.person))
  .then(response => {
    if(!response.ok) {
      throw Error("Network Request Failed");
    }
    return response
  })
  .then(d => d.json())
  .then(d => {
    this.setState({
      cardData: d
    })

    fetch(`http://localhost:3008/planets/${d.homeworld}`)
      .then(data => data.json())
      .then(data => {
        this.setState({
          homeData: data
        })
      })
  }, () => {
    this.setState({
      requestFailed: true
    })
  })

将它们提取到单独的函数中以对其进行清理会有所帮助。

于 2017-07-09T21:10:14.600 回答