简体   繁体   English

修改 React Google Chart 中的数据

[英]Modify data in React Google Chart

i'm learning react and i getted API data but i don't know how can i display in React Google Charts.我正在学习反应,我得到了 API 数据,但我不知道如何在 React Google 图表中显示。 The format to show in React Google Charts is like this:在 React Google Charts 中显示的格式是这样的:

['Germany', 200,0],
['United States', 300,0],
['Brazil', 400,0],
['Canada', 500,0],
['France', 600,0],
['RU', 700,0],

This is my code:这是我的代码:

import React, { useState, useEffect } from "react";
import Chart from "react-google-charts";

const Map = ({ url }) => {
    const [stats, setStats] = useState(null);
    const [values, setValues] = useState([]);

    const getData = async () => {
        const data = await fetch(url);
        const json = await data.json();
        setStats(json);

        for (const key in json) {
            values.push([json[key].country, json[key].active, json[key].deaths]);
        }
        console.log(values);
        // ["Afghanistan", 5717,169] --> I receive the data perfectly but i don't know how can i display it below     
    };

    useEffect(() => {
        getData();
    }, []);
    return (
        <div className="col-xl-12 text-center mb-3">
            <h4>Hover on map to see...</h4>
            <Chart
                width={"100%"}
                height={"350px"}
                chartType="GeoChart"
                options={{
                    displayMode: "regions",
                    backgroundColor: "#81d4fa",
                    colorAxis: {
                        values: [1000, 10000, 50000, 100000, 1000000],
                        colors: ["#00bc8c", "#f39c12", "#e74c3c", "red", "darkred"],
                    },
                }}
                data={[
                    ["Country", "Active cases", "Deaths"],
                    values.map(value => value + ",") //i tried this...
                ]}
                // Note: you will need to get a mapsApiKey for your project.
                // See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
                mapsApiKey="AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY"
                rootProps={{ "data-testid": "1" }}
            />
        </div>
    );
};

export default Map;

I commented the line with my fail tries.我用我的失败尝试评论了这条线。 I tried a lot of things but i can't show the data received我尝试了很多东西,但我无法显示收到的数据

Thanks for your time谢谢你的时间

You need to run setValues after you load your json data.加载 json 数据后,您需要运行setValues The changes you make to values don't take effect until you run setValues .在运行setValues之前,您对values所做的更改不会生效。

Also, although values feels like a list, perhaps consider avoiding using it directly with .push or similar.此外,虽然values感觉像是一个列表,但也许可以考虑避免将它直接与.push或类似的东西一起使用。 Instead, create a local copy of its current state, and then run setValues when you have the data for the map:相反,创建其当前 state 的本地副本,然后在您拥有 map 的数据时运行setValues

    useEffect(() => {
        const getData = async () => {
            fetch(url)
            .then(data => data.json())
            .then(json => {
               setStats(json);

               let myVals = [];
               for (let key in json) {
                  const { country, active, deaths } = json[key];
                  myVals.push([country, active, deaths]);
               }
               setValues(myVals);
             });
        };
        getData();
    }, []);

But if you're just reassigning that data with the same order then there could be a way to simplify it with map , something along the lines of:但是,如果您只是以相同的顺序重新分配该数据,那么可能有一种方法可以使用map来简化它,类似于:

const newValues = json.map(key => {
   const { country, active, deaths } = json[key];
   return [country, active, deaths];
});
setValues(newValues);

And you could safely condense that into one line, doesn't use push etc.你可以安全地将它压缩成一行,不使用push等。

I also needed to make it only render the <Chart> element after the data was loaded, so I'm using a separate state variable for that, along the lines of:我还需要在加载数据后使其仅呈现<Chart>元素,因此我为此使用了一个单独的 state 变量,如下所示:

    [dataLoaded, setDataLoaded] = useState(false),

...

    setValues(newValues);
    setDataLoaded(true);

...

    return <div>{
      dataLoaded ?
      <Chart
          chartType="..."
          data={[
           ['Country', 'Active', 'Deaths'],
           ...values
          ]} /> :
      null}
    </div>;

You could maybe just use the length of values or similar as a flag to refactor it, rather than a separate variable altogether.您可以只使用值的长度或类似的值作为标志来重构它,而不是完全使用单独的变量。

I also ended up putting the column headers into the state variable as well, so that the data attribute for the <Chart> is just the name of the variable.最后我还将列标题也放入了 state 变量中,这样<Chart>data属性就是变量的名称。 Mine is:我的是:

    [dataLoaded, setDataLoaded] = useState(false),
    [googleData, setGoogleData] = useState([]),
...
    const googleFormattedData = dataReturnedToGoogleData(0, data);
    let va = googleData;
    va[j] = googleFormattedData;
    setGoogleData(va);
    setDataLoaded(true);
...
 (within a loop)
    <Chart 
       data={
          googleData[data.optionNumber]
      } />

Not running setValues is the main issue with your version.不运行setValues是您的版本的主要问题。

Personally I'd avoid using the word json as a variable name, even though it's not reserved when it's lowercase.就我个人而言,我会避免使用json这个词作为变量名,即使它在小写时没有保留。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM