首页 > 解决方案 > 如何在 React 的 API 请求中传递参数?

问题描述

我正在进行 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;

标签: reactjsecmascript-6

解决方案


试试这种方式:

   
 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


推荐阅读