react 18 及配套路由及状态管理的应用

文章介绍了如何在React项目中集成react-router-domv6来管理路由,包括包裹根组件、创建路由数组以及在组件中引用。同时,文章也展示了如何使用Redux和@reduxjs/toolkit进行状态管理,包括创建store、定义reducer和asyncThunk,以及在组件中使用useDispatch和useSelector。最后,文章提到了路由参数的传递和获取方法。
摘要由CSDN通过智能技术生成

react-router-dom6的使用

首先安装

npm install  react-router-dom

紧接着在react index.tsx 文件夹中包裹根组件

import { Suspense } from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { Provider } from "react-redux";
const root = ReactDOM.createRoot(
  document.getElementById("root") as HTMLElement
);
root.render(
  <Provider store={store}>
    <BrowserRouter>
      <Suspense fallback={<div>加载中</div>}>
        <App />
      </Suspense>
    </BrowserRouter>
  </Provider>
);

 之后创建 routes数组

import { lazy } from "react";
import { RouteType } from "../api/data";

const Login = lazy(() => import("../pages/login/index"));

const My = lazy(() => import("../pages/my/index"));

const routes: RouteType[] = [
  {
    path: "/",
    element: <Login />,
  },
  {
    path: "/my/:name/:age",
    element: <My />,
  }
];

export default routes;

在跟组件中引用该数组

import React from "react";
import { useRoutes } from "react-router-dom";
import routes from "./router/index";
const App: React.FC = () => {
  return <div className="App">{useRoutes(routes)}</div>;
};

export default App;

 状态管理的使用

npm install react-redux  @reduxjs/toolkit

创建 store 文件夹 下边index.ts代码如下

import { configureStore } from '@reduxjs/toolkit'

import user from './modules/user'

export default configureStore({
    reducer: {
        user
    }
})

在store 文件夹下创建modules 文件夹 在下边创建 user.ts 文件

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { UserInputType } from "../../api/data"
import http from "../../api/index"



const userSlice = createSlice({
    name: "user",
    initialState: {
        id: "",
        username: "",
        key: "",
        privateKey: "",
        walletAddress: "",
        mnemonic: "",
        balance: 0,
        permissions: false,
    },
    reducers: {
        getconfig(state, action) {
            return { ...state, balance: action.payload.age }
        }
    },
    extraReducers: (builder) => {
        builder
            .addCase(fetchConfig.pending, state => {
              
            })
            .addCase(fetchConfig.rejected, state => {
            
            })
            .addCase(fetchConfig.fulfilled, (state,action:any) => {
             
                return {...state,...action.payload.data}
               
            })
    }


})

export const fetchConfig = createAsyncThunk(
    'user/fetchConfig',
    async (data: UserInputType) => {
        try {
            console.log(data)
            const res = await http("/createWallet", "POST", data);
            return res;
        } catch (err: any) {
            throw new Error(err.message);
        }
    }
);

export const { getconfig } = userSlice.actions

export default userSlice.reducer

在login 模块他的使用如下

import React from "react";
import { useDispatch, useSelector } from "react-redux";
import {useNavigate} from "react-router-dom"
import { StateType } from "../../api/data";
import { getconfig, fetchConfig } from "../../store/modules/user";
import "./index.scss"
const Login: React.FC = () => {
  const { balance,username } = useSelector((state: StateType) => state.user);

  const navigate = useNavigate()

  const dispatch = useDispatch();

  const add = () => {
    dispatch(getconfig({ name: "wangchangshuai", age: 18 }));
  };
  const getData = () => {
    dispatch(fetchConfig({ username: "ccc" }) as any);
  };
  const jump = ()=>{
    navigate("/my/wcs/18?name=wcd&age=90",{replace:true})
  }
  return (
    <div className="login">
      <div className="pan">{username+balance}</div>
      <button className="add" onClick={add}>
        加
      </button>
      <button onClick={getData}>请求</button>
      <button className="jump" onClick={jump}>跳转</button>
    </div>
  );
};

export default Login;

 路由传值也能看到

import {useNavigate} from "react-router-dom"

navigate("/my/wcs/18?name=wcd&age=90",{replace:true})


在my页面 

import React from "react";
import { useParams,useSearchParams } from "react-router-dom";

const My: React.FC = () => {
  const param = useParams();
   获取的值为对象是在 routes 的文件按中配置好的
   可参考routes的配置
  {
    path: "/my/:name/:age",
    element: <My />,
  }
  则param  = {name:"xxx",age:"xxxx"}


  url上的这一段可以使用 ?name=wcd&age=90

  const [SearchParams,setSearchParams] = useSearchParams();

  setSearchParams({ name: 'John', age: '30' }); 用来改变 ?name=wcd&age=90 属性的值
    SearchParams.get("name") 可以根据key获取值
  console.log(SearchParams.get("name"))
  return <div className="my">My</div>;
};

export default My;

  

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值