开发者问题收集

REECT中的图表JS未获取数据

2020-11-27
352

我创建了一个冠状病毒表,每当有人点击特定国家的名称时,模态框就会弹出活跃病例图表。 我意识到这可能是从 Bootstrap 导入的模态组件的问题(但不太确定)。当我将动画设置为 false 时,图表不会在 每个 模态框打开时显示数据。当不包含动画道具时,数据 有时 不会加载。关闭并重新打开几次可以解决问题。

  <Modal show={show} onHide={handleClose}
        animation={false}
        size="lg"
        aria-labelledby="contained-modal-title-vcenter"
        centered />


const Chart = ({CountryName}) => {
    const[data, setData] = useState({});
    let caseDate = [];
    let active = [];
    let confirmed = [];
    let deaths = [];
    let caseDatesSubstracted = [];

    const activeChart = () => {
        setData({
            labels: caseDatesSubstracted,
            datasets: [
                {
                    label: 'Active Cases',
                    data: active,
                    backgroundColor: [
                        ['black']
                    ],
                }
            ]
        })
    }
useEffect(() => {
        const loadData = async() => {
          await fetch(`https://api.covid19api.com/total/dayone/country/${CountryName}`)
          .then(response => response.json())
          .then(data => {
            for(const dataObj of data) {
                console.log(data)
                caseDate.push(dataObj.Date);
                active.push(dataObj.Active);
                confirmed.push(dataObj.Confirmed)
                deaths.push(dataObj.Deaths)
            }
            for(let i = 0; i < caseDate.length; i++){
                caseDatesSubstracted.push(caseDate[i].substring(0, caseDate[i].length-10));
            }
          })
          }
          loadData();
          activeChart();
          confirmedChart();
          deathChart();
    }, []);

    return(
        <div className="chart">
            <h1 style={{margin: '50px 0'}}>Active Cases</h1>
            <Line
            data={data}
            />
        </div>
    )
}
1个回答

尝试将所有内容像这样移入 useEffect。 不要混合状态和“let”变量。

我不确定这两个函数的作用,但不建议在函数内部使用这些变量。

    confirmedChart();
    deathChart();

试试这些。

const Chart = ({ CountryName }) => {
  const [data, setData] = useState({});


  const activeChart = (caseDatesSubstracted) => {
        //if u want to separate, then pass in the arg.
        setData({ .... }) // now u can use caseDatesSubstracted here.
  }



  useEffect(() => {
    const loadData = async() => {
      await fetch(`https://api.covid19api.com/total/dayone/country/${CountryName}`)
        .then(response => response.json())
        .then(data => {
          //do not declare them outside useEffect as they get re-initialize on every render.
          let caseDate = [];
          let active = [];
          let confirmed = [];
          let deaths = [];
          let caseDatesSubstracted = [];

          for (const dataObj of data) {
            console.log(data)
            caseDate.push(dataObj.Date);
            active.push(dataObj.Active);
            confirmed.push(dataObj.Confirmed)
            deaths.push(dataObj.Deaths)
          }
          for (let i = 0; i < caseDate.length; i++) {
            caseDatesSubstracted.push(caseDate[i].substring(0, caseDate[i].length - 10));
          }

          //set ur state here.
          /* alternatively, use activeChart(caseDatesSubstracted) by passing in the variable */
          setData({
            labels: caseDatesSubstracted,
            datasets: [{
              label: 'Active Cases',
              data: active,
              backgroundColor: [
                ['black']
              ],
            }]
          })
        })
    }
    loadData();
    confirmedChart(); //not good, move them. follow what I did for activeChart()
    deathChart(); // not good, move them. follow what I did for activeChart()
  }, []);


}
Someone Special
2020-11-27