首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何不一次抓取所有接口数据

如何不一次抓取所有接口数据
EN

Stack Overflow用户
提问于 2018-06-08 07:30:43
回答 2查看 126关注 0票数 1

嘿,伙计们,我已经设法让我的星球大战api数据从json显示在我的应用程序上。我通过将状态设置为people.name来获得name对象,但是当我将其设置为“people”时,它会呈现所有内容,包括我不想使用的数据。

代码语言:javascript
复制
class Card extends Component {
  constructor(){
    super()
    this.state = {
  jedi: [],
   searchfield: ''
}
    }

        componentDidMount(){
         fetch('https://swapi.co/api/people/1')
      .then(response => { return response.json()})
       .then(people => this.setState({jedi: JSON.stringify(people)}))
        }

    render(){
      return (
           <div className = 'charcards'>
             <div>
             <img className= 'pic' alt = 'Luke Skywalker' src = {luke} />
                </div>
                <hr/>
         <h2  className = "name1"> Name: {this.state.jedi.name}</h2>
         <h2 className = 'height'> {this.state.jedi.height}</h2>
          </div>
      );
    }

  }

如果我把.then(people => this.setState({jedi: JSON.stringify(people)}))改成

代码语言:javascript
复制
.then(people => this.setState({jedi: JSON.stringify(people.name)}))

但是我无法调用我的其他数据,比如高度、质量等。当我只是调用人们时,它调用了大量不必要的数据。如果我循环遍历api并挑选出我想要的数据,那么当我尝试遍历它但无法呈现数据时,我该如何处理呢?调用this.state.jedi.namethis.state.jedi.height并不起作用,因为它只是调用所有内容

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-06-08 08:31:58

在API支持之前,您不能获取部分数据。例如,你总是可以只使用你想要的。找到有用的源码...

代码语言:javascript
复制
    class Card extends Component {
      constructor(){
        super()
        this.state = {
      jediBio: {},
       searchfield: ''
    }
        }

            componentDidMount(){
             fetch('https://swapi.co/api/people/1')
          .then(response => { return response.json()})
           .then(people => this.setState({jediBio: people}))
            }

        render(){
//Define luke here else will throw luke as undefined
Let luke = "http://media.comicbook.com/2017/03/star-wars-luke-skywalker-239385.png";
          return (
               <div className = 'charcards'>
                 <div>
                 <img className= 'pic' alt = 'Luke Skywalker' src = {luke} />
                    </div>
                    <hr/>
             <h2  className = "name1"> Name: {this.state.jediBio.name}</h2>
             <h2 className = 'height'> {this.state.jediBio.height}</h2>
              </div>
          );
        }
     }
票数 0
EN

Stack Overflow用户

发布于 2018-06-08 08:00:11

我认为问题出在下面这一行:

.then(people => this.setState({jedi: JSON.stringify(people)})

您正在对response对象调用JSON.stringify(),它会将其序列化为一个字符串。如果您希望能够访问响应JSON的属性,您可以删除它以获取:

.then(people => this.setState({jedi: people})

而且,您的this.state.jedi状态看起来是一个数组,因此在检索nameheight属性时,要确保遍历每个this.state.jedi,而不是执行this.state.jedi.<name | height>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50751453

复制
相关文章

相似问题

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