zheng 19 часов назад
Родитель
Сommit
4bf88257d8

+ 21 - 0
19.React/高阶/project2/src/hooks/useAuth.js

@@ -0,0 +1,21 @@
+/**
+ * 自定义hook
+ * 1.hook函数 必须以 'use' 开头命名
+ * 2.自定义hook中可以使用任意内置的所有hook函数
+ */
+
+import { useEffect } from "react";
+import { useLocation, useNavigate } from "react-router-dom";
+const whiteList = ['/home','login'];
+export function useAuth() {
+    let location = useLocation();
+    let navigation = useNavigate();
+    let token = localStorage.getItem("token");  
+    useEffect(()=>{
+        if(!token && !whiteList.includes(location.pathname)) {
+            navigation({
+                pathname:"/my",
+            },{ state: { key: location.pathname } })
+        }
+    },[location])
+}

+ 3 - 1
19.React/高阶/project2/src/pages/Detail.jsx

@@ -1,9 +1,11 @@
-import { useNavigate, useParams, useSearchParams } from "react-router-dom";
+import { useLocation, useNavigate, useParams, useSearchParams } from "react-router-dom";
 function Detail() {
     const {ids} = useParams();
     const [searchPrams,setSearchPrams] = useSearchParams();
     console.log(searchPrams.get('id'),'ww')
     const navigate = useNavigate();
+    const location = useLocation();
+    console.log(location,'loca')
     function toList() {
         navigate({
             pathname:'/list'

+ 1 - 1
19.React/高阶/project2/src/pages/Error.jsx

@@ -3,4 +3,4 @@ function Error() {
         <h1>当前页面不存在!!!</h1>
     )
 }
-export default Error;
+export default Error;

+ 6 - 1
19.React/高阶/project2/src/pages/List.jsx

@@ -1,5 +1,6 @@
 import { useState } from "react";
 import { Link } from "react-router-dom";
+import { useAuth } from "../hooks/useAuth";
     const initState = [
         {
             id:1,
@@ -21,6 +22,7 @@ import { Link } from "react-router-dom";
         },
     ]
 function List() {
+    useAuth()
     let [fruit,setFruit] = useState(initState);
     const renderList = () => fruit.map((item,index) => <tr key={item.id}>
         <td>{index + 1}</td>
@@ -37,7 +39,10 @@ function List() {
                 pathname: '/detail',
                 search:`?id=${item.id}`
             }}>去详情</Link> */}
-            <Link to={`/detail?id=${item.id}`}>去详情</Link>
+            {/* <Link to={`/detail?id=${item.id}`}>去详情</Link> */}
+            <Link to={{
+                pathname:"/detail"
+            }} state={{ some: "222" }} >去详情</Link>
         </td>
     </tr> )
     // console.log

+ 3 - 0
19.React/高阶/project2/src/pages/My.jsx

@@ -1,4 +1,7 @@
+import { useLocation } from "react-router-dom";
 function My() {
+    let location = useLocation();
+    console.log(location)
     return <div>
         <h1>我的</h1>
     </div>