如何在React中从SWAPI检索数据

时间:2018-12-26 20:54:44

标签: reactjs fetch fetch-api

需要对SWAPI进行多次抓取

我想显示角色的电影和物种信息。我设法进行了初步提取,为我提供了物种和电影的名称以及网址,但无法理解如何在CardComponent中将它们显示为字符串

https://scrimba.com/c/cDrN9Tb->我在此scrimba中复制了我的项目。请检查一下。

应用组件

    class App extends Component {
      constructor(props) {
        super(props)
        this.state = {
          data: [],
          films: [],
          species: '',
        }

      }

      componentDidMount() {
        const url = 'https://swapi.co/api/people/';

        fetch(url)
          .then(response => response.json())
          .then(people => this.setState({ data: people.results }));

        }



      render() {
        const { data } = this.state;
        return (
          <div className='App'>
              <NavBar />
              <Header />
              {
                data.length === 0
                ? <h3>Loading Cards...</h3>
                : <h3>Cards Count: {data.length}</h3>
              }
              <CardContainer data={data} />
          </div>
        );
      }
    }

卡组件

    const CardComponent = ({ name, species, films }) => {

      return (
        <div className='Card'>
          <h3>{ name }</h3>
          <h4 style={{fontStyle: 'italic'}}>The species.name value should be shown below... not the url</h4>
          <h4>{ species }</h4>
          <div>Featured in:
            <p style={{fontStyle: 'italic'}}>(movie titles should be show in the list below, not the urls...)</p>
              <ul>
                {films.map((film, i) => (
                  <li key={i}>
                    { film }
                  </li>
                ))}
              </ul>
          </div>
        </div>
      )
    }

我只是新手,无法提出解决方案。阅读我可以找到的所有与swapi-react相关的条目,但是解决这一问题仍然不走运。请耐心等待= P

-编辑---

Species problem solved thanks to SakoBu

1 个答案:

答案 0 :(得分:0)

快速又肮脏的解决方案...将您的Card Component更改为此,您将根据需要显示物种...

import React from 'react';

export default class CardComponent extends React.Component {
  state = { species: '' };
  componentDidMount() {
    fetch(this.props.species[0])
      .then(response => response.json())
      .then(json => this.setState({ species: json.name }));
  }
  render() {
    return (
      <div className="Card">
        <h3>Name: {this.props.name}</h3>
        <h4 style={{ fontStyle: 'italic', color: 'red' }}>
          The species.name value should be shown below... not the url
        </h4>
        <h4>Species: {this.state.species}</h4>
      </div>
    );
  }
}