本篇内容介绍了“react项目中如何使用插件配置路由”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
react路由中没有安全守卫
推荐使用插件完成
react-router-waiter
网址
https://www.npmjs.com/search?q=react-router-waiter
react-router v6 路由统一管理 及 路由拦截方案。
安装
cnpm i --save-dev react-router-waiter"react-router-waiter": "^1.1.7",
用法
//引入路由import { BrowserRouter as Router } from "react-router-dom";//封装了内部的Routes组件import RouterView from "react-router-waiter";//引入路由配置和守卫import { routes, beforeRouter } from "./router/index";export default () => {return (<><Router><RouterView routes={routes} onRouteBefore={beforeRouter}></RouterView></Router></>);};
react-router-waiter组件提供了Routes和onrouterbefore API
Routes 路由配置
onRouteBefore 路由前置守卫
//创建路由配置export const routes = []; //创建路由前置守卫export const beforeRouter = () => {};
路由配置列表
//创建路由配置//引入同步组件import Index from "../views/Index";import Login from "../views/Login";import NotFound from "../views/Not-found";//component属性使用()=>import//element 同步export const routes = [{path: "/admin",element: <Index />,meta: {name: "系统首页",},},{path: "/login",element: <Login />,},{path: "/not-found",element: <NotFound />,},{path: "/",redirect: "/admin",},{path: "*",redirect: "/not-found",},];//react项目中配置 同步路由组件component属性换位 element属性 走同步 //如果组件使用异步载入 使用component//创建路由配置//引入同步组件import Index from "../views/Index";import Login from "../views/Login";import NotFound from "../views/Not-found";//component属性使用()=>import//element 同步export const routes = [{path: "/admin",component: () => import("../views/Index"),meta: {name: "系统首页",},},{path: "/login",component: () => import("../views/Login"),},{path: "/not-found",component: () => import("../views/Not-found"),},{path: "/",redirect: "/admin",},{path: "*",redirect: "/not-found",},] //()=>import(“***”)//底层 React.lazy(()=>import(""));
二级子路由配置
{path: '/',element: <PageLayout />, // 父级的公共组件使用element配置children: [... // 子级可以继续使用component配置]},
二级路由写法
{path: "/admin",// element: <Index />,component: () => import("../views/Index"),children: [{path: "index",component: () => import("../views/children/Index"),},{path: "user",component: () => import("../views/children/User"),},],meta: {name: "系统首页",},},//使用该插件避免闪屏//建议父级同步 子集懒加载{path: "/admin",element: <Index />,children: [{path: "index",component: () => import("../views/children/Index"),},{path: "user",component: () => import("../views/children/User"),},],meta: {name: "系统首页",},},
路由守卫
const onRouteBefore = ({ pathname, meta }) => {// 示例:动态修改页面titleif (meta.title !== undefined) {document.title = meta.title}// 示例:判断未登录跳转登录页if (meta.needLogin) {if (!isLogin) {return '/login'}}} export default onRouteBefore
使用守卫做登录认证
//创建路由前置守卫export const beforeRouter = ({ pathname, meta }) => {console.log(pathname, meta);//检测用户是否登录let token = localStorage.getItem("_token");console.log(token);if (token) {if (pathname == "/login") {return "/admin";}} else {return "/login";}};
状态机redux
中文文档
https://www.redux.org.cn/
Redux 是 JavaScript 状态容器,提供可预测化的状态管理。
redux由来
Redux 由 Flux 演变而来
如何使用redux
安装redux
npm install --save redux
附加包
npm install --save react-reduxnpm install --save-dev redux-devtools
redux不是react内置库属于第三方库文件。
项目中使用redux库
安装redux"redux": "^4.2.1",
main.js直接使用redux
//操作redux//1.引入redux redux插件使用的是单暴漏模式 不是export default//2.解出API 18里面使用legacy_createStore 之前使用createstore API//3.使用api 创建唯一store(store对象) 唯一是整个项目就这一个store对象import { legacy_createStore } from "redux";//4.创建store对象 参数必填 reducer 函数const store = legacy_createStore();console.log(store);
定义reducer函数,创建store对象
import { legacy_createStore } from "redux";//4.创建store对象 参数必填 reducer 函数//5.定义reducer 函数function reducer() {}const store = legacy_createStore(reducer);console.log(store);
创建store对象调用createStore API 默认执行reducer函数
function reducer() {console.log("测试");}const store = legacy_createStore(reducer);console.log(store);
默认执行reducer的作用是,创建store执行reducer获取默认的状态值。
//action 为触发的动作指令function reducer(state, action) {console.log("测试", state, action);}const store = legacy_createStore(reducer);console.log(store);//redux底层执行动作{type: '@@redux/INITt.0.e.r.j.b'} 执行该动作执行reducer获取默认值。
state设置初始状态值
//定义初始化状态let initialState = {count: 0,isShow: false,};//reducer形参//state状态值//action 为触发的动作指令function reducer(state = initialState, action) {console.log("测试", state, action);return state;}const store = legacy_createStore(reducer);//获取store state状态值console.log(store.getState());
使用dispatch触发action执行reducer修改state状态值
dispatch: ƒ dispatch(action)
//错误写法
store.dispatch("INCREMENT");
dispatch({type:"动作"})
import { legacy_createStore } from "redux";//4.创建store对象 参数必填 reducer 函数//5.定义reducer 函数 //定义初始化状态let initialState = {count: 0,isShow: false,};//reducer形参//state状态值//action 为触发的动作指令function reducer(state = initialState, action) {//获取action typelet { type } = action;switch (type) {case "INCREMENT":state.count++;return state; default:return state;}}const store = legacy_createStore(reducer);//获取store state状态值console.log(store, store.getState());//使用store对象api 执行动作触发修改state状态值store.dispatch({ type: "INCREMENT" });console.log(store.getState());
redux工作流程
redux和React关联
使用附加包npm install --save react-redux"react-redux": "^8.0.5",
项目中用法:
//引入react-redux//Provider reactredux内置组件限定范围传值import { Provider } from "react-redux";ReactDOM.createRoot(document.getElementById("root")).render(<React.StrictMode>{}<Provider store={store}><App /></Provider></React.StrictMode>);
关联之后函数组件中使用方案
//引入react-redux//useDispatch dispatch 触发action//useSelector getState获取状态值import { useDispatch, useSelector } from "react-redux";export default () => {return <>系统首页</>;}; //函数组件使用使用react-redux hook 完成状态值修改//引入react-redux//useDispatch dispatch 触发action//useSelector getState获取状态值import { useDispatch, useSelector } from "react-redux";export default () => {//获取store状态值let { count } = useSelector((state) => state);let dispatch = useDispatch();let increment = () => {dispatch({ type: "INCREMENT" });};let decrement = () => {dispatch({ type: "DECREMENT" });};return (<>系统首页-{count}<button onClick={increment}>++</button><button onClick={decrement}>--</button></>);};
存在一个问题,state状态值更新界面没有更新
原因试store对象中监听不到state对象变更
修改在reducer中修改完成state状态值之后需要断链return { ...state };return Object.assign({}, state);
“react项目中如何使用插件配置路由”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注编程网网站,小编将为大家输出更多高质量的实用文章!