如何在状态更改时阻止 useQuery 运行? [英] How to prevent useQuery for running when state changes?
问题描述
我正在使用 React Apollo 从我的服务器获取数据.当我的页面加载时,我使用 useQuery 来检索数据.这工作正常.问题是当我对搜索表单进行更改时,这会更新状态,从而导致不必要的重新渲染,从而再次调用服务器.
I am using React Apollo to get data from my server. When my page loads I am using useQuery to retrieve the data. This works fine. The problem is when I make a change to the search form, this updates the state which causes an unwanted re-render which calls the server again.
我只想在页面加载和点击搜索按钮时调用服务器.
I want to call the server only when the page loads and when I click the search button.
使用查询:
const { loading: loadingLessons, error: lessonsError, data: lessons } = useQuery(
LESSON_BY_PARAMS,
{
variables: { findLessonsInput: searchParams },
},
);
当我更改表单字段时,它会调用 updateFormField 更新 redux 状态,从而导致重新渲染
When I change a form field it calls updateFormField which updates the redux state causing a re-render
<Autocomplete
options={categories}
getOptionLabel={(option: any) => option.label}
inputValue={form.category}
defaultValue={() => {
const value = categories.find(option => option.label === form.category);
return value;
}}
onChange={(event, value) => updateFormField('category', value?.label)}
renderInput={params => (
<TextField {...params} label="Category" variant="outlined" fullWidth />
)}
/>
我正在使用 React 钩子.
I am using react hooks.
推荐答案
感谢@Vadim Sheremetov 的建议,但我决定将 api 调用移至 redux-thunk 函数:
Thanks for the suggestion @Vadim Sheremetov however I decided to move the api call to a redux-thunk function:
当页面加载时,我分派一个动作传递给它搜索参数和 apollo 客户端:
When the page loads I dispatch an action passing it search params and apollo client:
const client = useApolloClient();
useEffect(() => {
loadLessons(searchParams, client);
}, [location.search]);
const mapDispatchToProps = dispatch => {
return {
loadLessons: (searchParams, client) =>
dispatch(loadLessonsAction(searchParams, client)),
};
};
该操作调用一个 redux thunk 函数,然后该函数会调度另一个更新状态的操作:
The action invokes a redux thunk function which then dispatches another action that updates the state:
actions.ts:
actions.ts:
export function loadLessonsAction(searchParams: any, client: ApolloClient<object>):
any {
return async function(dispatch) {
try {
const { data } = await client.query({
query: LESSON_BY_PARAMS,
variables: { findLessonsInput: searchParams },
});
dispatch(loadLessonsSuccessAction(data.lessonsByParams));
} catch (error) {}
};
}
export function loadLessonsSuccessAction(lessons: any[]): FilterPanelActionTypes {
return {
type: LOAD_LESSONS_SUCCESS,
payload: lessons,
};
}
reducer.ts:
reducer.ts:
case LOAD_LESSONS_SUCCESS: {
return {
...state,
lessons: action.payload.lessons,
lessonCount: action.payload.count,
};
}
这篇关于如何在状态更改时阻止 useQuery 运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!