在多个组件中使用此挂钩时,如何防止多个数据获取?当URL保持不变时,仅当searchQuery
更改时,才不需要重新获取它。我还希望能够使用所有组件中的参数来调用loadPeople()
。
我尝试执行的操作是在执行people.data
之前检查fetchData()
是否已填充,但是那样loadPeople()
将永远无法工作。
type UseStarWarsProps = {
people: AsyncData<ApiStarWarsPerson[]>;
loadPeople: (query?: string) => void;
};
export const useStarWars = (): UseStarWarsProps => {
const [searchQuery, setSearchQuery] = useState('');
const people: AsyncData<ApiStarWarsPerson[]> = useSelector((state: RootState) => state.starWars.people);
const apiProxy: ApiProxyType = ApiProxy();
let dispatch = useDispatch();
const fetchData = async () => {
dispatch(setLoaderStarWarsAction());
try {
const data = await apiProxy.getStarWarsPeople(searchQuery);
dispatch(setStarWarsAction(data.results));
} catch (e) {
dispatch(setErrorStarWarsAction(e));
}
};
useEffect(() => {
fetchData();
}, [searchQuery]);
const loadPeople = (query?: string) => {
setSearchQuery(query || '');
};
return { people, loadPeople };
};