简体   繁体   English

防止在 React useState 中加载具有默认值的组件

[英]Prevent loading components with default values in React useState

I am working with offset pagination in typescript react.我正在打字稿反应中使用偏移分页。

I have two states that contain pageNumber and offset .我有两个包含pageNumberoffset The default page is set to 1 and the default offset is set to 0 as you can see below.默认页面设置为1 ,默认偏移设置为0 ,如下所示。

useState Hook useState钩子

  const [currentPage, setCurrentPage] = useState(1);
  const [calculatedOffset, setCalculatedOffset] = useState(0);

On load, the component fetches pageNumber and calculatedOffset from the localStorage and updates the defaults of the useState values.加载时,组件从localStorage获取pageNumbercalculatedOffset并更新 useState 值的默认值。

useEffect Hook useEffect挂钩

  useEffect(() => {
    if (typeof window !== "undefined") {
      const integerPage = parseInt(localStorage.getItem("currentPage") || "1");
      setCurrentPage(integerPage);

      const integerOffset = parseInt(localStorage.getItem("calculatedOffset") || "0");
      setCalculatedOffset(integerOffset);
    }
  }, []);

THE PROBLEM:问题:

The problem I am facing is that whenever the component loads, it loads up with the values of the default state, ie pageNumber: 1, calculatedOffset: 0 for half a second then changes it to the updated state that was which was updated when the useEffect hook ran.我面临的问题是,每当组件加载时,它都会加载默认状态的值,即pageNumber: 1, calculatedOffset: 0半秒,然后将其更改为更新状态,即useEffect时更新的状态钩跑了。 So on every load, the component flashes the data of the default state before ending up from the updated state fetched from localStorage.因此,在每次加载时,组件都会在从 localStorage 获取的更新状态结束之前刷新默认状态的数据。

Is there a way I can make it where the component only loads when the states have ended up on their final values and prevent the old states flashing for half a second behaviour every time the component loads?有没有一种方法可以让组件仅在状态最终达到最终值时加载,并防止每次加载组件时旧状态闪烁半秒?

useEffect runs when the component has been rendered fully. useEffect在组件完全渲染后运行。 So before that happens, useState is already used to initialise the variables according to which your components are initially rendered.所以在这之前, useState已经被用来初始化你的组件最初呈现的变量。

To prevent the initial render according to the initialised value from useState , set both to null in useState and in the component, render the elements conditionally:为了防止根据useState的初始化值进行初始渲染,在useState和组件中将两者都设置为nulluseState渲染元素:

{!currentPage || element}

or或者

{currentPage && element}

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

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