React - 更新多个 useEffect / useCallback 依赖项但只调用一次效果
React - update multiple useEffect / useCallback dependencies but only call effect once
我有一个分页数据列表,我正在根据过滤器和偏移量(页面)更新这些数据
更新偏移量时(next/prev 页),我点击 API 并获取新数据。更新过滤器后,我将偏移量重置为 0。
问题是,当更新过滤器和更新偏移量时,它会导致 useEffect 被触发两次。依次调用 api 两次。
const [filter, setFilter] = useState('All');
const [offset, setOffset] = useState(0);
onFilterChange = (value) => {
setFilter(value);
offset !== 0 && setOffset(0);
}
getDataFromAPI = useCallback(() => {
const endpoint = `https://example.com/data?filter=${filter}&offset=${offset}`;
CallApi(endpoint);
}, [offset, filter])
useEffect(getDataFromAPI, [getDataFromAPI]);
我认为解决方法是在这种情况下删除 useEffect
。有时它被不必要地使用。只需使用设置的新值在 onFilterChange
和 onOffsetChange
处理程序中调用 CallApi
,就是这样。
以下是 Dan Abramov 的一些相关引述:
In hindsight, my personal conviction has become that if some effect
can’t safely over-fire (e.g. fire twice instead of once), there is a
problem. Usually things that can’t over-fire are related to user
actions ("buy", "send", "finish"). Actions start in event handlers.
Use them!
To sum up, if something happens because a user did something,
useEffect might not be the best tool.
On the other hand, if an effect merely synchronizes something (Google
Map coordinates on a widget) to the current state, useEffect is a good
tool. And it can safely over-fire.
PS 但请注意,我认为在您的情况下,React 会在过滤器更改处理程序中对两个不同的设置状态调用进行批处理(因此调用一次渲染),但它似乎没有?无论如何,您可能仍然更喜欢我回答开头的建议,即删除 useEffect
.
我有一个分页数据列表,我正在根据过滤器和偏移量(页面)更新这些数据 更新偏移量时(next/prev 页),我点击 API 并获取新数据。更新过滤器后,我将偏移量重置为 0。
问题是,当更新过滤器和更新偏移量时,它会导致 useEffect 被触发两次。依次调用 api 两次。
const [filter, setFilter] = useState('All');
const [offset, setOffset] = useState(0);
onFilterChange = (value) => {
setFilter(value);
offset !== 0 && setOffset(0);
}
getDataFromAPI = useCallback(() => {
const endpoint = `https://example.com/data?filter=${filter}&offset=${offset}`;
CallApi(endpoint);
}, [offset, filter])
useEffect(getDataFromAPI, [getDataFromAPI]);
我认为解决方法是在这种情况下删除 useEffect
。有时它被不必要地使用。只需使用设置的新值在 onFilterChange
和 onOffsetChange
处理程序中调用 CallApi
,就是这样。
以下是 Dan Abramov 的一些相关引述:
In hindsight, my personal conviction has become that if some effect can’t safely over-fire (e.g. fire twice instead of once), there is a problem. Usually things that can’t over-fire are related to user actions ("buy", "send", "finish"). Actions start in event handlers. Use them!
To sum up, if something happens because a user did something, useEffect might not be the best tool.
On the other hand, if an effect merely synchronizes something (Google Map coordinates on a widget) to the current state, useEffect is a good tool. And it can safely over-fire.
PS 但请注意,我认为在您的情况下,React 会在过滤器更改处理程序中对两个不同的设置状态调用进行批处理(因此调用一次渲染),但它似乎没有?无论如何,您可能仍然更喜欢我回答开头的建议,即删除 useEffect
.