微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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;
  };
},[]);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。