[英]ReactJS ESlint hook error React Hooks must be called in the exact same order in every component render
I am getting an error from ESlint regarding how I am using hooks when rendering my React component.我从 ESlint 收到一个关于我在渲染 React 组件时如何使用钩子的错误。
React Hook "useReactiveVar" is called conditionally. React Hooks must be called in the exact same order in every component render
React Hook "useReactiveVar" is called conditionally. React Hooks must be called in the exact same order in every component render
.eslintreact-hooks/rules-of-hooks React Hook "useReactiveVar" is called conditionally. React Hooks must be called in the exact same order in every component render
.eslintreact-hooks/rules-of-hooks
Below is my code.下面是我的代码。 How can I resolve this?
我该如何解决这个问题?
import { useEffect } from 'react';
import { useApolloClient, useReactiveVar } from '@apollo/client';
import isClient from 'commons/isClient';
import useVisitorLocationHook from '../useVisitorLocationHook';
import ClosestOrderSampleValue from './ClosestOrderSampleValue';
import storesData from './stores.json';
const useClosestStoreOrderSample= () => {
const client = useApolloClient();
const { closestOrderSampleValueVar } = isClient() ? client.cache.jbReactiveVars : {};
const { loading = false, OrderSampleValue = null, forUserZip = null } = isClient()
? useReactiveVar(closestOrderSampleValueVar)
: {};
const [userLocation] = useVisitorLocationHook();
useEffect(() => {
if (!userLocation?.zip || userLocation?.zip === forUserZip) {
return;
}
ClosestOrderSampleValue.fetchClosestOrderSampleValuecode(client, userLocation.zip);
}, [userLocation]);
return {
storeLocation: isClient() && OrderSampleValue ? storesData[OrderSampleValue] : null,
isOrderSampleValueLoading: !userLocation?.zip ? false : loading,
};
};
export default useClosestStoreOrderSample;
As per the rules of hooks, you can't conditionally calla hook.根据钩子的规则,你不能有条件地调用钩子。 So this line:
所以这一行:
const { loading = false, OrderSampleValue = null, forUserZip = null } = isClient()
? useReactiveVar(closestOrderSampleValueVar)
: {};
is causing the error.导致错误。
You need to ensure that you call useReactiveVar()
without condition.您需要确保无条件调用
useReactiveVar()
。 For example, you could do this instead:例如,您可以这样做:
const clientData = useReactiveVar(closestOrderSampleValueVar);
const {
loading = false,
OrderSampleValue = null,
forUserZip = null,
} = isClient() ? clientData : {};
This will make sure that you always call the hooks in the same and correct order.这将确保您始终以相同且正确的顺序调用挂钩。 This is necessary as React uses the order in which hooks are called to ensure it updates the correct state through each render.
这是必要的,因为 React 使用调用钩子的顺序来确保它通过每个渲染更新正确的状态。 You can read more information (with examples) on this here .
您可以在此处阅读更多信息(带有示例) 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.