首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React:从嵌套数组中获取数据

React:从嵌套数组中获取数据
EN

Stack Overflow用户
提问于 2018-05-05 06:07:34
回答 1查看 942关注 0票数 1

5月4日,我想用this REST API做一个小小的星战反应应用。我从JSON获取数据,其中有几个嵌套数组,它们链接到不同的people,也返回更多的JSON。

我需要做的是找到一种很好的方法来从嵌套数组中获取数据,同时映射people JSON。

所以我的应用程序HTML最终看起来像这样

代码语言:javascript
复制
// this would be something like `<p>{ data.name }</p>`
<p>Name: Luke Skywalker</p>
// data data more data

// the `FILMS` array comes from `data.films` which only holds URL's
<div>
  <p>Films</p>
</div>
<div>
  <p>The Empire Strikes Back</p>
  <p>Revenge of the Sith</p>
  // return the rest of movies character was in
</div>

目前,我的想法是将CharData转换为一个类,在componentDidMount中有多个fetch调用,并希望它设置状态,从而在this.state对象上生成一个数组。但这将需要发生在每个单独的电影和所有我想要的是标题。只是看起来返回一个值有很多事情要做。

App.js

代码语言:javascript
复制
import React, { Component } from 'react';
import './App.css';

// components
import CharContainer from './comp/charcontainer/CharContainer';

class App extends Component {
  constructor() {
    super();
    this.state = {
      starwarsChars: []
    };
  }
  componentDidMount() {
    // feel free to research what this code is doing.
    // At a high level we are calling an API to fetch some starwars data from the open web.
    // We then take that data and resolve it our state.
    fetch('https://swapi.co/api/people')
      .then(res => {
        return res.json();
      })
      .then(data => {
        this.setState({ starwarsChars: data.results });
      })
      .catch(err => {
        throw new Error(err);
      });
  }
  render() {
    return (
      <div className="App">
        <h1 className="Header">React Wars</h1>

        {/* Char Container */
        (this.state.starwarsChars.length > 0)
          ?
            <CharContainer charData={ this.state.starwarsChars } />
          :
            <h2>Fetching Character Information...</h2>
        }
      </div>
    );
  }
}

export default App;

CharData.js

代码语言:javascript
复制
import React from 'react';

const CharData = props => {
  return (
    <React.Fragment>

      {
        props.charData.map((char, ind) => {
          return (
            <div className='char-card-container__char-card-wrapper'>
              <div key={ind + Date.now()} className="char-card-container__char-card">

                <h2 className='mt-2'>{char.name}</h2>
                <p className='mt-2'><span className='char-card__char-info-label'>Gender:</span> {char.gender}</p>
                <p className='mt-2'><span className='char-card__char-info-label'>Birth Year:</span> {char.birth_year}</p>
                <p className='mt-2'><span className='char-card__char-info-label'>Eye Color:</span> {char.eye_color}</p>
                <p className='mt-2'><span className='char-card__char-info-label'>Hair Color:</span> {char.hair_color}</p>
                <p className='mt-2'><span className='char-card__char-info-label'>Height:</span> {char.height}</p>
                <p className='mt-2'><span className='char-card__char-info-label'>Weight:</span> {char.mass}</p>
                <p className='mt-2'><span className='char-card__char-info-label'>Skin Color:</span> {char.skin_color}</p>

                <div className='mt-2'>
                  <div>
                    <p className='char-card__char-info-label'>Films</p>
                  </div>
                  <div>
                    {
                      char.films.map(film => {
                        return (
                          <p>{film}</p>
                        )
                      })
                    }
                  </div>
                </div>

                <div className='mt-2'>
                  <div>
                    <p className='char-card__char-info-label'>Specie</p>
                  </div>
                  <div>
                    {
                      char.species.map(specie => {
                        return (
                          <p>{specie}</p>
                        )
                      })
                    }
                  </div>
                </div>

                <div className='mt-2'>
                  <div>
                    <p className='char-card__char-info-label'>StarShips</p>
                  </div>
                  <div>
                    {
                      char.starships.map(starship => {
                        return (
                          <p>{starship}</p>
                        )
                      })
                    }
                  </div>
                </div>

                <div className='mt-2'>
                  <div>
                    <p className='char-card__char-info-label'>Vehicles</p>
                  </div>
                  <div>
                    {
                      char.vehicles.map(vehicle => {
                        return (
                          <p>{vehicle}</p>
                        )
                      })
                    }
                  </div>
                </div>

              </div>
            </div>
          );
        })
      }

    </React.Fragment>
  );
}

export default CharData;
EN

回答 1

Stack Overflow用户

发布于 2018-05-05 06:39:24

您可以呈现<FilmContainer film={film} />,而不是呈现<p>{film}</p>,其中film是一个URL,您可以使用与在App中类似的方式获取它。

你可能最终会得到很多这样的容器,用于不同种类的细节。解决重复问题的一种方法是使用Render Props方法。

代码语言:javascript
复制
class FetchContainer extends Component {
  constructor() {
    super();

    this.state = {
      loading: true,
      data: null
    };
  }

  componentDidMount() {
    fetch(this.props.url)
      .then(res => {
        return res.json();
      })
      .then(data => {
        this.setState({
          loading: false, 
          data,
        });
      })
      .catch(err => {
        throw new Error(err);
      });
  }

  render() {
    return this.props.children({
      loading: this.state.loading,
      data: this.state.data
    });
  }
}

以下是如何使用此组件以个人详细信息显示电影信息的方法:

代码语言:javascript
复制
{char.films.map(film => (
  <FetchContainer url={film}>
    {({ loading, data }) => loading ? (
      <p>Loading film...</p>
    ) : (
      <p>{data.title}</p>
    )}
  </FetchContainer>
))}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50183659

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档