简体   繁体   English

React Hooks:将来自 api 调用的数据映射到渲染饼图

[英]React Hooks : mapping data from api call to render pie chart

need some help here.在这里需要一些帮助。 Thank you!谢谢!

I am making a call to an api which returns an object with two numbers and a list, like so...我正在调用一个 api,它返回一个带有两个数字和一个列表的 object,就像这样......

{2, 1 , []}

The codebase I am working with is using 'use-global-hook' for Redux state management.我正在使用的代码库正在使用“use-global-hook”进行 Redux state 管理。 So I have storeState, storeActions as global hooks.所以我有 storeState、storeActions 作为全局钩子。

So in my render I have verified that the number values exist.所以在我的渲染中,我已经验证了数值存在。

return
(
  <h3> storeState.value1</h3>  //prints 2
  <h3> storeState.value2 </h3> //prints 1

)

Tried mapping this way and this throws too many renders error.尝试以这种方式映射,这会引发太多渲染错误。 How can I map the dataset to Pie chart?如何将数据集 map 转换为饼图?

const test1 = (props) => 
{

  const [piChartData, setpiChart] = useState({});

  React.useEffect(()=>{
    storeActions.callApi(); 
   },[]);

  function drawPieChart()
  {
    setpiChart({
       labels: ['label1', 'label2'],
       datasets:[{
                   data:[storeState.value1, storeState.value2],
                   backgroundColor: ['red','green']
                 }]
   })
 }

 return(
  {drawPieChart()}

   <Pie data={piChartData}/>
  )
 }

drawPieChart calls setpiChart updating the state and causing the component to re-render, on each render, you call drawPieChart , which calls setpiChart , causing an infinite loop of rendering, drawPieChart调用setpiChart更新 state 并导致组件重新渲染,在每次渲染时,您调用drawPieChart ,它调用setpiChart ,导致渲染无限循环,

remove drawPieChart() from render and put it in useEffect so it gets called when the component mounts, if callApi is aync and returns a promise , use .then :从渲染中删除drawPieChart()并将其放入useEffect以便在组件安装时调用它,如果callApi是 aync 并返回promise ,请使用.then

const test1 = (props) => {
  const [piChartData, setpiChart] = useState({});

  React.useEffect(() => {
    storeActions.callApi();
    drawPieChart();
    /**
     * OR
     * storeActions.callApi().then(() => drawPieChart(););    
     */
  }, []);

  function drawPieChart() {
    setpiChart({
      labels: ["label1", "label2"],
      datasets: [
        {
          data: [storeState.value1, storeState.value2],
          backgroundColor: ["red", "green"]
        }
      ]
    });
  }

  return <Pie data={piChartData} />;
};

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

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