如何在React中的API请求中传递参数?

时间:2019-03-11 03:35:19

标签: reactjs ecmascript-6

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

代码:

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;

1 个答案:

答案 0 :(得分: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'));

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