我正在创建一个ReactJS组件,它将使用API获取比特币,以太币和魔像的当前价格。到目前为止,我已经能够检索数据并将其输出到渲染功能中。但是,我希望价格保持刷新,而不是一次点击API,然后改变状态。这是我当前的组件
class PriceChecker extends React.Component {
constructor(){
super();
this.state = {
priceBtc: '00:00',
priceEth: '00.00',
priceGol: '00:00'
}
}
componentDidMount(){
fetch("https://coinmarketcap-nexuist.rhcloud.com/api/btc").then(request => request.json()).then(request => this.setState({priceBtc: request.price.usd}))
fetch("https://coinmarketcap-nexuist.rhcloud.com/api/eth").then(request => request.json()).then(request => this.setState({priceEth: request.price.usd}))
fetch("https://coinmarketcap-nexuist.rhcloud.com/api/gnt").then(request => request.json()).then(response => this.setState({priceGol: response.price.usd}))
}
render(){
return (
<div className="price">
<h1 className="headline-pr">Current Prices</h1>
<div className="price-container">
<div className="price-card">
<span>Bitcoin Price</span>
<h1>${this.state.priceBtc}</h1>
</div>
<div className="price-card">
<span>Ethereum Price</span>
<h1>${this.state.priceEth}</h1>
</div>
<div className="price-card">
<span>Golem Price</span>
<h1>${this.state.priceGol}</h1>
</div>
</div>
</div>
)
}
}
有没有什么方法可以让我每隔10秒左右再次点击API或至少刷新价格?
答案 0 :(得分:0)
您可以将componentDidMount
中的代码包装在setInterval
let timeinterval;
componentDidMount(){
timeinterval = setInterval(function() {
fetch("https://coinmarketcap-nexuist.rhcloud.com/api/btc").then(request => request.json()).then(request => this.setState({priceBtc: request.price.usd}))
fetch("https://coinmarketcap-nexuist.rhcloud.com/api/eth").then(request => request.json()).then(request => this.setState({priceEth: request.price.usd}))
fetch("https://coinmarketcap-nexuist.rhcloud.com/api/gnt").then(request => request.json()).then(response => this.setState({priceGol: response.price.usd}))
}, 1000);
}
componentWillUnmount() {
clearInterval(timeinterval);
}