首页 > 解决方案 > 组件不会在 useEffect() 运行一次时呈现

问题描述

所以我有以下代码,我在其中获取要在我的组件中呈现的数据。但是,如果将 useEffect 设置为运行一次,它不会在组件内部渲染数据,并且一直运行它是不可持续的。

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


const Bottom5 = ({ company }) => {
    const [quiz, setQuiz] = useState('');
    const [dataPoints, setDatapoints] = useState([]);

    useEffect(() => {
            var resultData = [];
            fetch(`http://localhost:3001/company/dashboard/bottom5/${company}`)
            .then(function(response) {
                return response.json();
            })
            .then(function(data) {
                for (var i = 0; i < data.length; i++) {
                    resultData.push({
                        label: data[i].name,
                        y: data[i].sumCorrect
                    });
                }
               setDatapoints(resultData)
            });
    },[])


    return (
            <Chart style={{display:"inline-block"}}
                width={'500px'}
                height={'300px'}
                chartType="ColumnChart"
                loader={<div>Loading Chart</div>}
                data={[
                    ['Names', 'Result'],
                    ...dataPoints.map(d => [d.label, d.y])
                ]}
                options={{
                    title: 'CyberSecurity Bottom 5',
                    chartArea: { width: '50%' },
                    hAxis: {
                        title: 'Employees',
                        minValue: 0,
                    },
                    vAxis: {
                        title: 'Total Correct',
                    },
                }}
                // For tests
                rootProps={{ 'data-testid': '1' }}
            />
    )
}

export default Bottom5;

标签: javascriptreactjsreact-hooksreact-google-charts

解决方案


可能是当您第一次安装组件时您没有将 a 传递company给它吗?

通常,由于代码取决于 的值,因此添加到依赖项列表中company是个好主意。companyuseEffect

useEffect(() => {
  var resultData = [];
  if (company) {
    fetch(`http://localhost:3001/company/dashboard/bottom5/${company}`)
      .then(function(response) {
        return response.json();
      })
      .then(function(data) {
        for (var i = 0; i < data.length; i++) {
          resultData.push({
            label: data[i].name,
            y: data[i].sumCorrect
          });
        }
        setDatapoints(resultData)
      });
  }
}, [company])

company这样,只有在更改属性时才会调用它。


推荐阅读