2017-07-02 42 views
0

我正在创建一个ReactJS组件,它将使用API​​获取比特币,以太坊和魔像的当前价格。到目前为止,我已经能够检索数据并将其输出到渲染函数中。但是,我希望价格能够持续刷新,而不是一次点击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> 
    ) 
    } 
} 

有没有什么办法可以让我保持点击API或至少每10秒刷新一次价格?

回答

0

你可以换行代码componentDidMountsetInterval

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); 
} 
+0

我有点困惑,放在哪里让时间间隔声明 – alpha787

+0

您可以声明它的组件之外或作为成员你可以在'constructor()'中使用你的组件,并且可以用this.timeinterval来访问它。不知道哪一个是最好的。 – flocks