温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

react项目中如何使用插件配置路由

发布时间:2023-03-30 11:57:31 来源:亿速云 阅读:91 作者:iii 栏目:开发技术

本篇内容介绍了“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

1.Routes 路由配置

2.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: "系统首页",
},
},

路由守卫

/**
* @param {string} pathname 当前路由路径
* @param {object} meta 当前路由自定义meta字段
* @return {string} 需要跳转到其他页时,就返回一个该页的path路径,或返回resolve该路径的promise对象
*/
const onRouteBefore = ({ pathname, meta }) => {
// 示例:动态修改页面title
if (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-redux
npm 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);

react项目中如何使用插件配置路由

定义reducer函数,创建store对象

import { legacy_createStore } from "redux";
//4.创建store对象 参数必填 reducer 函数
//5.定义reducer 函数
function reducer() {}
const store = legacy_createStore(reducer);
console.log(store);

react项目中如何使用插件配置路由

创建store对象调用createStore API 默认执行reducer函数

function reducer() {
console.log("测试");
}
const store = legacy_createStore(reducer);
console.log(store);

react项目中如何使用插件配置路由

默认执行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());

react项目中如何使用插件配置路由

使用dispatch触发action执行reducer修改state状态值

dispatch: &fnof; dispatch(action)

//错误写法store.dispatch("INCREMENT");

react项目中如何使用插件配置路由

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 type
let { 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工作流程

react项目中如何使用插件配置路由

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>
{/* 将store对象关联到整个react项目 */}
<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项目中如何使用插件配置路由”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI