【问题标题】:How to pass parameters in API request in React?如何在 React 的 API 请求中传递参数?
【发布时间】:2019-03-11 03:35:18
【问题描述】:

我正在进行 API 调用,以响应将从加密货币 API 获取数据的位置。但我想获取特定加密货币的数据。我试图在 fetch 请求中定义一些逻辑,但它不起作用。我正在尝试在请求中添加“比特币”和“以太坊”作为参数。

代码:

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


class App extends Component {
  constructor(){
    super();
    this.state={
        data: [
            {
                name:'',
                id:'',
                symbol:'',
                price_usd:'',
                percent_change_1h:'',
                percent_change_24h:'',
                percent_change_7d:'',
                isLoading:true
            },
        ]
    }
    this.fetchData=this.fetchData.bind(this);
}

fetchData=()=>{
  fetch('https://api.coinmarketcap.com/v1/ticker/?limit=3')
  .then((response)=>{
  const wanted=['ethereum','bitcoin']
  const r=response.data.filter(currency=>
    wanted.includes(currency.id))
    this.setState({
      data:r,
      isLoading:false
    })})
    .catch(err=>alert("error"));
}

componentDidMount(){
  this.fetchData();
  this.interval = setInterval (() => this.fetchData (), 10*1000)
}
  render() {
    return (
      <div className="App">
      <div className="App-header">
      {this.state.isLoading?<Loading/>:
        <Crypto data={this.state.data}/>
      }
      </div>
      </div>
    );
  }
}

const Loading=()=>{
  return(
  <div>
    loading...
  </div>
  );
}
export default App;

【问题讨论】:

  • 你想要的最终请求 url 是什么?
  • 我想要变量“wanted”的数据
  • 你想如何将值传递给想要的 /https://api.coinmarketcap.com/v1/ticker/?wanted=ethereum,bitcoin
  • 你要请求的网址是什么?
  • https://api.coinmarketcap.com/v1/ticker/ 在他们的文档中提供对wanted 查询参数的支持?

标签: reactjs ecmascript-6


【解决方案1】:

试试这个方法:

   
 fetch('https://api.coinmarketcap.com/v1/ticker/?limit=3')
  .then((resp) => resp.json())
  .then(function(data){
      const wanted=['ethereum','bitcoin']
      const filtered=data.filter(currency=>{                       return wanted.includes(currency.id)
      });
    console.log(filtered);
  }).catch(err=>alert('error'));

在此处了解有关 fetch api 的更多信息:https://scotch.io/tutorials/how-to-use-the-javascript-fetch-api-to-get-data

【讨论】:

    猜你喜欢
    • 2021-09-24
    • 2022-10-06
    • 2017-04-10
    • 1970-01-01
    • 2021-02-01
    • 2018-11-06
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    相关资源
    最近更新 更多