【问题标题】:React Hook "useState" is called conditionally有条件地调用 React Hook “useState”
【发布时间】:2021-03-17 00:04:56
【问题描述】:

React 抱怨下面的代码,说它 useState 和 useEffect 被有条件地调用。没有打字稿,代码工作正常:

import React, { useState, useEffect } from "react";

const useScrollPosition = () => {
  if (typeof window === "undefined") return 500;

  // Store the state
  const [scrollPos, setScrollPos] = useState(window.pageYOffset);

  // On Scroll
  const onScroll = () => {
  setScrollPos(window.pageYOffset);
};

  // Add and remove the window listener
  useEffect(() => {
    window.addEventListener("scroll", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
    };
  });
};

export default useScrollPosition;

【问题讨论】:

    标签: reactjs typescript use-effect use-state


    【解决方案1】:

    你有一个提前返回,所以它被有条件地调用if (typeof window === "undefined") return 500;

    您需要在提早返回之前移动挂钩。有关详细说明,请阅读此https://reactjs.org/docs/hooks-rules.html

    【讨论】:

      【解决方案2】:

      将返回移动到函数底部并将空数组传递给useEffect的第二个参数,因为useEffect中存在的代码只运行一次。

      import React, {useState, useEffect} from "react";
      
      const useScrollPosition = () => {
          
      
          // Store the state
          const [scrollPos, setScrollPos] = useState(window.pageYOffset);
      
          // On Scroll
          const onScroll = () => {
              setScrollPos(window.pageYOffset);
          };
      
          // Add and remove the window listener
          useEffect(() => {
              window.addEventListener("scroll", onScroll);
              return () => {
                  window.removeEventListener("scroll", onScroll);
              };
          }, []); // set an empty array for run once existing code in the useEffect
      
         return typeof window === "undefined" ? return 500 : <></>; // a value must be returned
          
      };
      
      export default useScrollPosition;
      

      【讨论】:

        猜你喜欢
        • 2019-12-28
        • 2022-12-21
        • 1970-01-01
        • 2020-03-08
        • 2021-04-03
        • 2021-08-07
        • 2020-01-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多