只有当searchTerms
字符串改变时,我需要在useEffect钩子内调用logEvent函数。问题是total_result
等于前一个值的状态。所以我需要得到data?.hits.total.value
的最新值。这就是为什么我使用setTimeout来获取最新的值。是否可以不使用setTimeout:
const hitsRef = useRef<undefined | number>();
hitsRef.current = data?.hits.total.value;
useEffect(() => {
if (searchTerms) {
const log = setTimeout(() => {
analyticsService?.logEvent(ANALYTICS_EVENTS.SEARCH_COMPLETED, {
total_results: hitsRef.current,
error_message: null,
});
}, 2000);
return () => {
clearInterval(log);
};
}
}, [searchTerms]);
Btw如果我在useEffect数组中包含data?.hits.total.value
,它将记录我的函数2次。也因为在某些情况下total_results可以是相同的,所以它不会调用我的logEvent函数。
interface SearchResultsProps {
refinement: string;
searchTerms: string;
currentPage: number;
}
const SearchResults: FunctionComponent<SearchResultsProps> = ({
refinement,
searchTerms,
currentPage,
}) => {
const { formatMessage } = useIntl();
const { analyticsService } = useContainerProps();
const shouldRender = searchTerms.length > 0;
const { data, isFetching, isLoading } = usePagedQuery({
refinement,
terms: searchTerms,
count: recordsPerPage,
offset: (currentPage - 1) * recordsPerPage,
queryEnabled: shouldRender,
});
const hitsRef = useRef<undefined | number>();
hitsRef.current = data?.hits.total.value;
useEffect(() => {
if (searchTerms) {
const log = setTimeout(() => {
analyticsService?.logEvent(ANALYTICS_EVENTS.SEARCH_COMPLETED, {
total_results: hitsRef.current,
error_message: null,
});
}, 2000);
return () => {
clearInterval(log);
};
}
}, [searchTerms]);
...
你不需要使用setTimeout和useRef钩子。数据在哪儿? .hits.total。价值来自哪里?如果数据? .hits.total。value是一个道具,你最好保存为一个变量,并像这样直接传递到useEffect中:
const totalValue = data?.hits.total.value;
useEffect(() => {
if (searchTerms) {
analyticsService?.logEvent(ANALYTICS_EVENTS.SEARCH_COMPLETED, {
total_results: totalValue,
error_message: null,
});
return () => {
// clear request
};
}
}, [searchTerms, totalValue]);
现在如果searchTerms或totalValue被改变,useEffect重新渲染