反应实时图

时间:2018-07-24 08:57:30

标签: json reactjs graph

class Index extends React.Component {
    static async getInitialProps() {
        const url = "https://api.coindesk.com/v1/bpi/currentprice.json"
        const res = await fetch(url)
        const json = await res.json()
        const result = {
            key: dateFormat(new Date(), "isoDateTime")
        }
        Object.keys(json.bpi).map((item) => {
            result[item] = json.bpi[item].rate_float
        })
        return { bitcoin: result }
    }
    constructor(props) {
        super(props)
        this.state = {
            data: [this.props.bitcoin]
        }
        this.fetch = this.fetch.bind(this)
    }
    componentDidMount() {
        setInterval(() => {
            this.fetch()
        }, 2000)
    }
    async fetch() {
        const url = "https://api.coindesk.com/v1/bpi/currentprice.json"
        const res = await fetch(url)
        const json = await res.json()
        const result = await {
            key: dateFormat(new Date(), "isoDateTime")
        }
        Object.keys(json.bpi).map((item) => {
            result[item] = json.bpi[item].rate_float
        })
        const { data } = this.state
        data.push(result)
        this.setState({
            data: data,
        })
    } render() {
        const { data } = this.state
        console.log('render', data)
        return (
            <div>
                <LineChart width={600} height={300} data={data} >
                    <XAxis dataKey="key" />
                    <YAxis />
                    <CartesianGrid strokeDasharray="1 1" />
                    <Tooltip />
                    <Legend />
                    <Line type="monotone" dataKey="USD" />
                    <Line type="monotone" dataKey="GBP" />
                    <Line type="monotone" dataKey="EUR" />
                </LineChart>
            </div>
        )
    }
}

export default Index

此代码从https://api.coindesk.com/v1/bpi/currentprice.json获取数据 并且每2秒数据将更新一次,但graph只有1个数据,我感到困惑,因为在console.log(data)中每2秒增加数据 如何在该图中绘制另一个数据?

0 个答案:

没有答案