简体   繁体   English

React Hook "useState" 被有条件地调用。 在每个组件渲染错误中,必须以完全相同的顺序调用 React Hooks

[英]React Hook "useState" is called conditionally. React Hooks must be called in the exact same order in every component render error

I am encountering an error after a git merge (I accidently had eslint warnings turned off).我在 git 合并后遇到错误(我不小心关闭了 eslint 警告)。 However, I don't know what is exactly causing this error, and how I can fix it.但是,我不知道究竟是什么导致了这个错误,以及如何修复它。 The error is:错误是:

ERROR in [eslint] src/pages/PageHome.js Line 47:49: React Hook "useState" is called conditionally. [eslint] src/pages/PageHome.js 第 47:49 行中的错误:有条件地调用 React Hook “useState”。 React Hooks must be called in the exact same order in every component render react-hooks/rules-of-hooks React Hooks 必须在每个组件渲染中以完全相同的顺序调用 react-hooks/rules-of-hooks

Search for the keywords to learn more about each error.搜索关键字以了解有关每个错误的更多信息。

export default function PageHome() {
      var maxWebshopId = 0;
      const importedWebshopObject = JSON.parse(
        sessionStorage.getItem("client_shops")
      );
      function handleWindowSizeChange() {
        setWidth(window.innerWidth);
      }
      useEffect(() => {
        window.addEventListener("resize", handleWindowSizeChange);
        return () => {
          window.removeEventListener("resize", handleWindowSizeChange);
        };
      }, []);
    
      PrimeReact.ripple = true;
    
      const [width, setWidth] = useState(window.innerWidth);
      const isMobile = width <= 768;
    
      // Menu fold in/out state
      const [visible, setVisible] = useState(true);
      if (importedWebshopObject.length >= 1) {
        importedWebshopObject.forEach((element) => {
          console.log(element);
          if (parseInt(element.id) > maxWebshopId) {
            maxWebshopId = parseInt(element.id);
          }
        });
    
        const [WebshopOrderId, setWebshopOrderId] = useState(maxWebshopId);
        const value = { WebshopOrderId, setWebshopOrderId };
    
        return(
          <WebshopOrderIdContext.Provider value={value}>
            <div
              className='page-home'
              style={{ backgroundColor: "var(--surface-ground)" }}>
              <DashboardSidebar
                overlay={isMobile}
                visible={[visible, setVisible]}
              />
    
              <Menubar
                className='border-none pr-2 shadow-1 fixed z-5 w-full p-0'
                model={null}
                start={
                  !visible && (
                    <Button
                      icon='pi pi-bars'
                      className='p-button-secondary p-button-text p-3'
                      onClick={(e) => setVisible(true)}
                    />
                  )
                }
                end={
                  <div className='flex flex-row'>
                    <WebshopSwitcher />
                    <Divider className='m-0' layout='vertical' />
                    <LogoutButton />
                    <Divider className='m-0 mr-2' layout='vertical' />
                    <DarkModeButton />
                  </div>
                }
              />
              <div
                id='content-container'
                className='flex flex-row justify-content-center transition-duration-300'
                style={{
                  marginLeft: visible && !isMobile ? "20rem" : "0rem",
                  minHeight: "100vh",
                }}>
                <span className='spaced-container mt-6 w-full p-5'>
                  <Outlet />
                </span>
              </div>
            </div>
          </WebshopOrderIdContext.Provider>
        );
      }
      else {
        return(
          <div className='page-home'>
            <div className='flex flex-column flex-wrap justify-content-start align-items-start'>
              <h1 className='text-3xl font-bold m-6'>
                Je moet minstens één webshop op je account hebben om dit portaal te
                kunnen gebruiken.
              </h1>
              <Button
                label='terug naar de inlogpagina'
                className='p-button-primary p-button-outlined p-3 m-6'
                onClick={() => (window.location.href = "/login")}
              />
            </div>
          </div>
        );
      }
    }

Exactly what the error is telling you.正是错误告诉您的内容。 This is inside of an if block:这是在if块内:

const [WebshopOrderId, setWebshopOrderId] = useState(maxWebshopId);

React hooks don't allow that. React 钩子不允许这样做。 Each rendering of the component must call the same hooks in the same order.组件的每次渲染都必须以相同的顺序调用相同的钩子。 Move it outside of the if block, up to where your other useState call is:将其移到if块之外,直到您的其他useState调用所在的位置:

const [WebshopOrderId, setWebshopOrderId] = useState(maxWebshopId);
const [width, setWidth] = useState(window.innerWidth);
const isMobile = width <= 768;

Even if the component will only actually use that state based on a condition, the state still needs to exist regardless of that condition so the framework can manage it.即使组件仅根据条件实际使用state,state 仍然需要存在,无论该条件如何,框架都可以管理它。

暂无
暂无

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

相关问题 有条件地调用 React Hook “useCustomHook”。 在每个组件渲染中,必须以完全相同的顺序调用 React Hooks - React Hook "useCustomHook" is called conditionally. React Hooks must be called in the exact same order in every component render React Hook“useEffect”被有条件地调用。 React Hooks 必须在每个组件渲染中以完全相同的顺序调用 - React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render 错误:有条件地调用 React Hook “useCallback”。 在每个组件渲染中,必须以完全相同的顺序调用 React Hooks - Error: React Hook "useCallback" is called conditionally. React Hooks must be called in the exact same order in every component render useNameProps" 被有条件地调用。React Hooks 必须在每个组件渲染中以完全相同的顺序调用 - useNameProps" is called conditionally. React Hooks must be called in the exact same order in every component render ReactJS ESlint 钩子错误 React Hooks 必须在每个组件渲染中以完全相同的顺序调用 - ReactJS ESlint hook error React Hooks must be called in the exact same order in every component render 在构建应用程序时,必须在每个组件呈现错误中以完全相同的顺序调用 React Hooks - NextJs/Javascript - React Hooks must be called in the exact same order in every component render error when building app - NextJs/Javascript React Hook“useState”无法在 class 组件中调用。 React Hooks 必须在 React function 组件或自定义 React Hook function 中调用 - React Hook "useState" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function 必须以完全相同的顺序调用 React Hook 但我遇到了异常 - React Hook must be called in the exact same order BUT I got an exception 无法在顶层调用 React Hook“useNavigate”。 React Hooks 必须在 React function 组件或自定义 React Hook function 中调用 - React Hook "useNavigate" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function 错误:在 function 中调用了 React Hook “useState” - Error: React Hook "useState" is called in function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM