react18结合路由reuter@6——TS和redux的配合

Posted 勇敢*牛牛

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了react18结合路由reuter@6——TS和redux的配合相关的知识,希望对你有一定的参考价值。

利用react-router@6+TS完成路由的跳转与参数的接收


主要是对params参数做类型的限制。


import  useNavigate,useParams,useSearchParams,useLocation  from "react-router-dom"

const Detail = () => 
    const navigate = useNavigate()
    const params = useParams<uid:string>()//接收params参数
    const [search] = useSearchParams();
    const location = useLocation()

    return (
        <div>
            <h1>details</h1>
            <button onClick=()=>navigate('/about')>去关于页面</button>
            <hr />
            <div>
                动态路由参数:params.uid
                <hr></hr>
                搜索search参数:search.get("title")
                <hr></hr>
                state数据:location.state?.phone
            </div>
            
        </div>

    )


export default Detail

redux的配合

使用

yarn add @reduxjs/toolkit

导出类型

export interface Iadd
    num:number

接收类型

import type Iadd from "./typeings"

推荐对state类型的限制写法

import createSlice, PayloadAction from "@reduxjs/toolkit"
import type Iadd from "./typeings"
const countSlice = createSlice(
    name:"addcount",
    initialState:
        num:1000
     as Iadd,
    reducers:
        steNum(state,action:PayloadAction<number>)
            state.num += action.payload
        
    

)
export const steNum = countSlice.actions
export default countSlice.reducer


使用之前先对usedispatch和useSelector进行重构。

  • 首先对于store仓库源来获取所有的数据的类型,导出
import  configureStore from "@reduxjs/toolkit";
import addcount from "../components/Home/addcount";

const store =  configureStore(
    reducer:
        addcount
    
)

export type APPdispatchtype = typeof store.dispatch;
export type Rootstatetype = ReturnType<typeof store.getState>

export default store
  • 重构hooks函数的获取与派发;
import useSelector,useDispatch from "react-redux";
import type TypedUseSelectorHook from "react-redux" 

import Rootstatetype,APPdispatchtype from './index'

export const useAppDispatch = ()=>useDispatch<APPdispatchtype>();
export const useAppselector:TypedUseSelectorHook<Rootstatetype> = useSelector
  • 同步使用
import React from 'react'
import useAppselector,useAppDispatch from '@/store/hooks'
import steNum from './addcount'
const Home = ()=> 
    const addcount = useAppselector(state=>state.addcount.num);
    const dispatch = useAppDispatch();
  return (
    <>
        <h1>home-addcount</h1>
        <hr />
        <button onClick=e=>dispatch(steNum(2))>++++</button>
    
    </>
  )


export default Home
  • 异步存储

以上是关于react18结合路由reuter@6——TS和redux的配合的主要内容,如果未能解决你的问题,请参考以下文章

react结合ts与mobx环境搭建步骤详解

结合 React 路由器和 Firebase 函数 api

react18 + TS的webpack增量配置——使用craco/craco

react18 + TS的webpack增量配置——使用craco/craco

react的ts配置

网课代理合伙人2020黑马C++32期·React17 系统精讲 结合TS打造旅游电商平台~7··萌萌家IT会员