React.js:渲染时微调动画停止

问题描述

我制作了一个简单的微调器,将在此过程中显示。动画应该一直运行直到表格被渲染,但我的微调动画在获取数据时正在工作,但在渲染表格之前它只是停留了几秒钟。不知道是不是因为数据太多,渲染速度慢

我正在使用反应钩子...

 useEffect(async () => {
    if (spinner === null) {
      const tor = await axios.get("http://localhost:8080/api/tor");
      const uk = await axios.get("http://localhost:8080/api/uk");
      const ny = await axios.get("http://localhost:8080/api/ny");
      setInfo({
        tor: tor.data,uk: uk.data,ny: ny.data,});

      setSpinner(false);
    }
  },[]);
  let tables = null;

  if (info.tor != null) {
    console.log(info);
    tables = (
      <Container>
        <Element name="tor">
          <br />
          <h1 className="display-4">Toronto</h1>
          <Table info={info.tor} />
        </Element>
        <Element name="uk">
          <br />
          <h1 className="display-4">London</h1>
          <Table info={info.uk} />
        </Element>
        <Element name="ny">
          <br />
          <h1 className="display-4">New York</h1>
          <Table info={info.ny} />
        </Element>
      </Container>
    );
  }

  return (
    <div>
      <SearchContainer />
      {spinner === true || spinner === null ? (
        <Standby />
      ) : (
        <React.Fragment>{tables}</React.Fragment>
      )}
    </div>
  );

解决方法

  1. 尝试根据文档重构钩子内的异步函数代码,此处:https://github.com/facebook/react/issues/14326
  2. 考虑添加您认为合适的 Hook 依赖项:https://reactjs.org/docs/hooks-reference.html#conditionally-firing-an-effect
,

如上述帖子所述,我正在尝试将您的解决方案形象化

useEffect(() => {
  let isCancelled = false;
  setSpinner(true);

  async function test() {
     tor = await axios.get('http://localhost:8080/api/tor');
     uk = await axios.get('http://localhost:8080/api/uk');
     ny = await axios.get('http://localhost:8080/api/ny');
    
     setInfo({
      tor: tor.data,uk: uk.data,ny: ny.data,});
     
  }

  if (!isCancelled) {
    test();
    setSpinner(false);
  }

  return () => {
    isCancelled = true;
  };
},[]);