繁体   English   中英

使用useState挂钩的react组件是否会重新渲染每个setState调用?

[英]Does a react component using useState hook rerender every `setState` call?

https://codesandbox.io/s/mow5zl5729

import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import axios from "axios";

function useLoading() {
  const [isLoading, setLoading] = React.useState(true);
  const [hasError, setError] = React.useState(false);

  const loadStuff = aPromise => {
    return aPromise
      .then(() => {
        setLoading(false);
      })
      .catch(() => {
        setLoading(false);
        setError(true);
      });
  };

  return { isLoading, hasError, loadStuff };
}

function App() {
  const { isLoading, hasError, loadStuff } = useLoading();

  useEffect(() => {
    loadStuff(axios.get(`https://google.com`));
  }, []);

  console.log(isLoading, hasError);

  return <div />;
}

这是我的意思的简化示例。

如果useLoading内部的useLoading被拒绝,我希望组件在安装时呈现,然后在捕获错误时第二次呈现。 因此,我希望共有2个具有以下状态的渲染器:

第一个渲染:

  • isLoading:true
  • hasError:假

第二个渲染:

  • isLoading:否
  • hasError:true

相反,似乎组件在setLoading(false)之后setLoading(false)渲染一次,在setError(true)之后再次渲染一次。 所以,我得到这个:

第一个渲染:

  • isLoading:true
  • hasError:假

第二个渲染:( 为什么?)

  • isLoading:否
  • hasError:假

第三渲染:

  • isLoading:否
  • hasError:true

我怀疑问题出在某种程度上是我在useEffect使用了promise,但是我不确定我的思维模式出了什么问题。

编辑:

当我将useLoading更改为仅包含1 useState ,问题就消失了。

破碎:

const [isLoading, setLoading] = React.useState(true);
const [hasError, setError] = React.useState(false);

作品:

const [loadingState, setLoadingState] = React.useState({
  loading: true,
  error: false
});

看起来这与状态更新的批处理有关。 据我所知,基于React的事件将触发批处理更新,但不会触发在其外部触发的更新。 在这种情况下promise

由于状态调用未批处理,因此您会看到2nd render ,其中两个都设置为false

暂无
暂无

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

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