本篇文章中將會使用React搭配custom hook與localStorage來實作登入系統

這個登入系統會檢查使用者localStorage有沒有token,有的話才能正常顯示內容,沒有的話會顯示登入頁面。

這個方法不會重新導網址,因此不需要 /login 的路由,好處是使用者不會因為導址而丟失目前的路徑

參考來源:https://www.digitalocean.com/community/tutorials/how-to-add-login-authentication-to-react-applications

事前準備

$ npx create-react-app login-demo
$ cd login-demo
$ npm install react-router-dom
$ npm install --save-dev express cors

建立頁面

src/下建立components/,並建立三個頁面:

Page1.jsPage2.js (更改return內的內容)

export default function Dashboard() {
  return <h2>Page1</h2>;
}

Login.js 內容待會再實作