简体   繁体   English

异步渲染 React 组件(等待数据返回)

[英]Render React component asynchronously (wait for data to be returned)

I have the following ReactJS component :我有以下 ReactJS组件

import React, {useState} from 'react';
import Plot from 'react-plotly.js';

import {utility} from "./utility";

function Chart() {
    
    const [use_data, setData] = useState([]);

    const handleClick = () => {
        const newData = {
            x: ['giraffes', 'orangutans', 'monkeys'],
            y: [20, 14, 23],
            type: 'bar'
        }
        setData((use_data) => [...use_data, newData]);
    };

    return (
        <>
        <button onClick={handleClick}>GO</button>
        <Plot
            var data = {use_data}
            var layout={ {width: 1000, height: 400, title: "Top 100 Topics"} }
        />
        </>
    );

}

export default Chart;

It updates the hardcoded data to produce the following chart on button click:它更新硬编码数据以在按钮单击时生成以下图表:

在此处输入图像描述

Obviously I need to fetch my own data rather than hardcode it as above.显然,我需要获取自己的数据,而不是像上面那样对其进行硬编码。 In my utilites.js I produce data with the same structure shown above (newData), however it takes about a second to return this data.在我的 utilites.js 中,我生成了与上面所示结构相同的数据(newData),但是返回这些数据大约需要一秒钟。 Thus, React does not render the visual.因此,React 不会呈现视觉效果。

ReactJS is obviously looking for some kind of asynchronous state management in order to render this visual (render once data are returned). ReactJS 显然正在寻找某种异步 state 管理,以便呈现这种视觉效果(一旦返回数据就呈现)。

const handleClick = () => {
    const newData = utilities.fetch_data()
    setData((use_data) => [...use_data, newData]);
}; 

How can my above code be changed to allow for asynchonous rendering.如何更改我上面的代码以允许异步渲染。 Is this where a hook is needed to implement something similar to componentDidMount but for functional components?这是否需要一个钩子来实现类似于 componentDidMount 但功能组件的东西?

If I understand the problem correctly, you should use Promise when fetching data, after that, you need a utility to format the response something like the following example:如果我正确理解问题,您应该在获取数据时使用Promise ,之后,您需要一个实用程序来格式化响应,如下例所示:

const formatter = (statics) => {
  const tmp = statics.map((static) => {name: static.name, .......});

  return tmp;
};

function App() {
  const [state, setState] = React.useState(null);

  React.useEffect(() => {
    fetch('https://blahblahblah.com')
      .then((res) => res.json())
      .then((response) => {
        return formatter(response.data.statics);
      })
      .then((formatedData) => setState(formatedData));
  }, []);

  return <h1>{state ? JSON.stringify(state) : "wait..."}</h1>;
}

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

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