【发布时间】:2021-08-04 08:51:06
【问题描述】:
我有一个获取一堆帖子的组件。这也有一组过滤器。
const [selectedCountry, setSelectedCountry] = useState(null);
const [selectedStatus, setSelectedStatus] = useState(null);
const getPosts = async (payload) => {
const response = await fetchPosts(payload);
return response;
};
const payload = {
country: selectedCountry,
status: selectedStatus,
};
const {isLoading, data: posts} = useQuery(['posts', payload], () => getPosts(payload));
const handleApplyFilters = () => {
// refecth the posts with the applied filter payload
}
return (
<>
<select
name="countryFilter"
value={selectedCountry}
onChange={(e) => {
setSelectedCountry(e.target.value);
}}>
<option>Singapore</option>
<option>Finland</option>
<option>Portugal</option>
</select>
<select
name="statusFilter"
value={selectedStatus}
onChange={(e) => {
setSelectedStatus(e.target.value);
}}>
<option>Online</option>
<option>Offline</option>
<option>Blocked</option>
</select>
<button onClick={handleApplyFilters}>
Apply Filters
</button>
{posts.map((post) => (
<div>
<div>{post.title}</div>
<div>{post.description}</div>
</div>
))}
</>
)
我不确定如何使用 react-query 实现以下目标。
- 仅在初始渲染期间获取帖子
- 避免在每次过滤器更改时获取帖子(仅在单击
Apply Filter按钮时重新获取)
【问题讨论】:
标签: reactjs react-query