我有一个用例,页面必须在第一次渲染和单击按钮时调用相同的获取函数。
代码类似于以下内容(参考: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
我有以下组件:
\nimport 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) 我正在尝试使用 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 在第一个示例中警告我?
在这种情况下我可以安全地忽略它吗?
我写了这个钩子(可能有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)
在这种用法中,我希望收到通知a,b, 和c需要位于依赖项数组中。
我有一个关于 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) 当您调用“内置”钩子之一时,该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) 我正在尝试实现 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 之外,我还应该使用其他东西吗?