router 要使用時,會在hook內呼叫 useHistory 來操作,但是如果你是在其他共用的地方要觸發換頁,直接這樣使用是會出錯的。


以往我們在使用router,會這樣使用:

import { BrowserRouter } from "react-router-dom";
<BrowserRouter>
  <Layouts />
</BrowserRouter>

然後如果要在頁面內呼叫:

import { useHistory } from "react-router-dom";
const Home = () => {
  const history = useHistory();
  const handleLogout = async () => {
    history.push("/Login");
  };
  //... return 
}

可是有時候我們不一定會在頁面內使用,可能要在一些共用的event handler呼叫,這時候就要改寫一下history這個function的創建方式。

新增一隻檔案 history.js

import { createBrowserHistory } from "history";
export default createBrowserHistory();

 

BrowserRouter 改成用 Router

import { Router } from "react-router-dom";
import history from "@/utils/history"
<Router history={history}>
  <Layouts />
</Router>

 

在event handler中使用

import history from "@/utils/history"

export const handleSomeEvent = () => {
  history.push("/Login");
}
0
0 回復

發表評論

想要加入討論嗎?
請盡情發表您的想法!

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。