【问题标题】:react-query: How to fetch during the initial render and when an action is triggerdreact-query:如何在初始渲染期间以及触发操作时获取
【发布时间】: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 实现以下目标。

  1. 仅在初始渲染期间获取帖子
  2. 避免在每次过滤器更改时获取帖子(仅在单击 Apply Filter 按钮时重新获取)

【问题讨论】:

    标签: reactjs react-query


    【解决方案1】:

    payload 放入queryKey 就对了。现在您要做的就是在选择某些内容时不立即更新该本地状态,而仅在用户点击应用时更新。为此,我会将过滤器放入它自己的组件中,它自己的状态将仅在单击应用时设置有效负载:

    const [payload, setPayload] = React.useState(null)
    
    const {isLoading, data: posts} = useQuery(['posts', payload], () => getPosts(payload));
    
    
    <FilterForm onApply={setPayload} />
    

    FilterForm 然后将包含两个选择的状态,当单击应用按钮时,它将构建有效负载并调用onApply,然后它将调用父级中的setPayload,从而触发重新-获取。

    【讨论】:

      猜你喜欢
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 2022-11-22
      • 2021-12-15
      • 1970-01-01
      • 2016-02-05
      • 1970-01-01
      • 2021-06-05
      相关资源
      最近更新 更多