【问题标题】:Re-fetch with useSWR hook when React Router Param changed当 React Router 参数更改时使用 useSWR 钩子重新获取
【发布时间】:2023-02-05 02:39:33
【问题描述】:

我发现了很多与此类似的问题,但它们都使用正常的抓取,可以通过 useEffect 挂钩处理,但使用 useSWR 是不可能的。

继承人的代码:

// simplified Router component:
export default function Router(){
  <BrowserRouter>
      <Routes>
        <Route path="/" element={<Layout />}>
          <Route index element={<MainPage />} />
          <Route path="post/:id" element={<Post />} />
        </Route>
      </Routes>
    </BrowserRouter>
}

// Post.tsx
export default function Post(){
  const {id} = useParams()
  const i = parseInt(id)
  const fetcher = (url) => axios.get(url, {id: i}).then(res => res.data)
  const {data} = useSWR('http://localhost:80/post', fetcher)
  return <div>
           {/*display post content */}
         </div>
}

我尝试使用 useNavigate() 重定向/重新加载,但没有成功。

【问题讨论】:

    标签: javascript reactjs react-router react-router-dom swr


    【解决方案1】:

    你可以重新验证(mutate) 如果参数useEffect 内的变化。

    const { data, mutate } = useSWR('http://localhost:80/post', fetcher);
    
    useEffect(() => {
       mutate('http://localhost:80/post', fetcher);
    }, [param]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-01
      • 2020-03-30
      • 2021-06-23
      • 2019-12-20
      • 1970-01-01
      • 1970-01-01
      • 2020-06-01
      • 2015-12-27
      相关资源
      最近更新 更多