标签: eslint-plugin-react-hooks

与 useEffect 一起使用时如何防止 useCallback 触发(并遵守 eslint-plugin-react-hooks)?

我有一个用例,页面必须在第一次渲染和单击按钮时调用相同的获取函数。

代码类似于以下内容(参考:https ://stackoverflow -question-bink-62951987?file=index.tsx):

import React, { FunctionComponent, useCallback, useEffect, useState } from 'react';
import { fetchBackend } from './fetchBackend';

const App: FunctionComponent = () => {
  const [selected, setSelected] = useState<string>('a');
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<boolean>(false);
  const [data, setData] = useState<string | undefined>(undefined);

  const query = useCallback(async () => {
    setLoading(true)

    try {
      const res = await fetchBackend(selected);
      setData(res);
      setError(false);
    } catch (e) {
      setError(true);
    } finally {
      setLoading(false);
    }
  }, [])

  useEffect(() …
Run Code Online (Sandbox Code Playgroud)

javascript typescript reactjs react-hooks eslint-plugin-react-hooks

9
推荐指数
1
解决办法
3825
查看次数

React Hooks 详尽的异步无限循环

我有以下组件:

\n
import React, { useState, useEffect } from "react";\n\nconst App = () => {\n    const [data, setData] = useState<null | any[]>(null);\n    const [checked, setChecked] = useState(false);\n    const [loading, setLoading] = useState(false);\n\n    useEffect(() => {\n        setLoading(true);\n\n        (async () => {\n            if (data) {\n                // Could do something else here if data already exsisted\n                console.log("Data exists already");\n            }\n\n            const ret = await fetch("https://jsonplaceholder.typicode.com/users?delay=1000", { cache: "no-store" });\n            const json = await ret.json();\n            setData(json);\n            setLoading(false);\n        })();\n\n    }, [checked]);\n\n    return (\n        <>\n            <h1>useEffect …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs react-hooks eslint-plugin-react-hooks

8
推荐指数
1
解决办法
2917
查看次数

为什么 `react-hooks/exhaustive-deps` lint 规则会在嵌套对象属性上触发?

我正在尝试使用 React hooks 来记忆回调。此回调专门使用在对象上定义的函数。

const setValue = useCallback((value) => {
    field.setValue(key, value);
}, [field.setValue, key]);
Run Code Online (Sandbox Code Playgroud)

这会触发 Eslint 规则react-hooks/exhaustive-deps
它想让我进去[field, key]

如果我将代码更改为以下内容,即使看起来等效,我也不会收到警告:

const { setValue: setFieldValue } = field;

const setValue = useCallback((value) => {
  setFieldValue(key, value);
}, [setFieldValue, key]);
Run Code Online (Sandbox Code Playgroud)

为什么 Eslint 在第一个示例中警告我?
在这种情况下我可以安全地忽略它吗?

eslint react-hooks usecallback eslint-plugin-react-hooks

7
推荐指数
1
解决办法
1391
查看次数

我可以为自定义钩子设置 react-hooks/exhaustive-deps 吗?

我写了这个钩子(可能有bug,我还没用过):

import { useCallback, useEffect } from 'react';
import _throttle from 'lodash/throttle';

export function useThrottledCallback(cb, delay, ...deps) {
  const callback = useCallback(_throttle(cb, delay), deps);

  useEffect(() => {
    const lastCallback = callback;

    return () => lastCallback.cancel();
  }, [callback]);

  return callback;
}
Run Code Online (Sandbox Code Playgroud)

有没有办法可以使这个钩子的详尽的 deps 规则 lint 用法?

useThrottledCallback(() => (a + b + c)}, 100, [])
Run Code Online (Sandbox Code Playgroud)

在这种用法中,我希望收到通知ab, 和c需要位于依赖项数组中。

reactjs eslint react-hooks eslint-plugin-react-hooks

7
推荐指数
1
解决办法
745
查看次数

带有依赖列表和 eslint-plugin-react-hooks 的自定义钩子

我有一个关于 eslint-plugin-react-hooks 的问题。

我想减少执行 API 调用并将结果存储到状态的样板代码,所以我创建了一个自定义钩子:

export const loading = Symbol('Api Loading');
export const responseError = Symbol('Api Error');

export function useApi<T>(
    apiCall: () => CancelablePromise<T>,
    deps: DependencyList
): T | (typeof loading) | (typeof responseError) {
    const [response, setResponse] = useState<T | (typeof loading) | (typeof responseError)>(loading);
    useEffect(() => {
        const cancelablePromise = apiCall();
        cancelablePromise.promise
            .then(r => setResponse(r))
            .catch(e => {
                console.error(e);
                setResponse(responseError);
            });
        return () => cancelablePromise.cancel();
    }, deps); // React Hook useEffect has a missing dependency: 'apiCall'. Either …
Run Code Online (Sandbox Code Playgroud)

reactjs eslint react-hooks eslint-plugin-react-hooks

5
推荐指数
1
解决办法
1365
查看次数

如何让eslint的react-hooks/exhaustive-deps规则知道自定义hooks的返回值是不变的?

当您调用“内置”钩子之一时,该react-hooks/exhaustive-deps规则足够智能,可以识别出 React 保证某些返回值是不变的。useState这是由和钩子返回的状态更新器和调度器的情况useReducer

在第一个示例中,调用useCallback不需要将状态设置器列为依赖项:

export const Example1 = () => {
  const [date, setDate] = useState(new Date())

  const resetDate = useCallback(() => {
    setDate(new Date())
  }, []) // No need to list any dependency here. No eslint warning.

  return (
    <>
      Date: {date.toISOString()} <button onClick={resetDate}>Reset</button>
    </>
  )
}
Run Code Online (Sandbox Code Playgroud)

但在第二个示例中,setter 由自定义挂钩返回,这是必需的。

const useDateState = (initialValue: Date) => {
  return useState(initialValue)
}

export const Example2 = () => {
  const [date, setDate] = useDateState(new …
Run Code Online (Sandbox Code Playgroud)

reactjs eslint react-hooks eslint-plugin-react-hooks

5
推荐指数
0
解决办法
635
查看次数

反应 useEffects 详尽的 deps 仅触发创建组件才会卸载功能

我正在尝试实现 useEffect 回调以在卸载组件之前分派操作。此操作的目的是存储组件的最后状态,以便下次加载该组件时可以从该状态恢复。我只希望在卸载时触发此回调。

当尝试为我的 useEffect 使用空依赖项数组时,反应推荐的“eslint-plugin-react-hooks”中的“exhaustive-deps”规则要求我包含我试图保留的值。这会导致每次存储状态时都会触发效果和操作。

有没有比禁用此行的 eslint 更好的方法来处理这种情况?

这就是我想要的:

...
const [value, setValue] = useState('');

useEffect(() => {
    return () => {
        storeValueAction(value);
    };
}, []);
...
Run Code Online (Sandbox Code Playgroud)

eslint-plugin-react-hooks 想要它并导致在每次状态更改时调度操作的方式:

...
const [value, setValue] = useState('');

useEffect(() => {
    return () => {
        storeValueAction(value);
    };
}, [value, storeValueAction]);
...
Run Code Online (Sandbox Code Playgroud)

除了 useEffect 之外,我还应该使用其他东西吗?

javascript reactjs use-effect eslint-plugin-react-hooks

1
推荐指数
1
解决办法
753
查看次数