reactjs - 如何在 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;
解决方案
试试这种方式:
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
推荐阅读
- node.js - 如何解决错误:找不到模块“ejs”?
- flutter - 如何在颤动中使用带有 Bloc 的冷冻包?
- android - Android edittext 视图在文本输入时被修剪
- reactjs - 面临错误:输入是一个空元素标签,既不能有 `children`,也不能使用 `dangerouslySetInnerHTML`。在创建一个简单的表单时
- angular - 从源“http://localhost:4200”访问“https://exam.com/api/Uni/GetAll”的 XMLHttpRequest 已被 CORS 策略阻止
- java - 在 Java SWT GUI 中显示 Excel 文件的内容
- php - PHP Klein 未捕获错误:错误的参数
- azure-resource-manager - ARM 模板 - 在两个嵌套模板之间创建依赖关系
- android - 如何确保在多次按下按钮后仅打开一次活动
- php - 注册后,当我转到主页时出现错误 - “尝试获取非对象的属性 'blog_name'”