React18+typescript+react-redux基础配置实现

510 阅读2分钟

react18.1.0使用Typescript开发项目配置react-reudx基础配置实现

React typescript react-redux基础配置实现

React typescript react-redux

react:18.1.0
react-dom: 18.1.0
react-redux:8.0.2

我一样推崇看文档解决问题,线上文档链接 TypeScript Quick Start | React Redux原文文档 React Redux | Redux 中文官网


在使用ts开发react项目中我们要配置react-redux进行一些数据管理,因为react16.x以后进入hook的开发方式,所以各种包针对hook的更新也就开始更新了,下面我们看一下react使用ts开发如何配置react-redux

项目的结构

编辑

添加图片注释,不超过 140 字(可选)

  1. component放置组件和每个组件的reducer(也可以放置在store文件夹中reducer目录下面进行管理)

  2. 文件夹routers对所有的路由进行管理

  3. 文件夹store下面的index就是最终向外暴露的store

  4. 在src/index.js对store进行全局注入

component/home/Home.tsx

import { useDispatch, useSelector } from 'react-redux'
import { increment, decrement,incrementByAmount } from './homeReducer'
import { RootState} from '../../store/index'


const Home = () => {
    const count = useSelector((state:RootState) => state.user.value)// 使用useSelector进行获取数据操作
    console.log(count)
    const dispatch = useDispatch() // 使用dispatch进行派发操作
    return <>
        <h1>Home</h1>
        <h2>{count}</h2>
        <button onClick={() => dispatch(increment())}>+</button>
        <button onClick={() => dispatch(decrement())}>-</button>
        <button onClick={() => dispatch(incrementByAmount(10))}>++</button>
    </>;
}

export default Home

component/home/homeReducer.ts

import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import type { RootState } from '../../store/index'

interface CounterState { // 定义初始化状态的类型
    value: number
}
const initialState: CounterState = { // 初始化状态
    value: 33,
}
export const counterSlice = createSlice({
    name: 'counter',
    initialState,
    reducers: {
        increment: (state) => {
             state.value += 1
        },
        decrement: (state) => {
            state.value -= 1
        },
        incrementByAmount: (state, action: PayloadAction<number>) => {
            state.value += action.payload
        },
    },
})

export const { increment, decrement, incrementByAmount } = counterSlice.actions // 导出操作state的喊出
export const selectCount = (state: RootState) => state
export default counterSlice.reducer // 导出当前reducer在store/index.ts中记性全局挂载(这种也可以不用挂载到全局)

store/index.ts

import { configureStore } from '@reduxjs/toolkit'
import counterSlice from '../component/home/homeReducer'

const store = configureStore({
    reducer: {
        user: counterSlice
    },
})

export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch

export default store

src/index.tsx

import React from 'react';
import ReactDOM from 'react-dom/client';
import Routers from './routers/Routers';
import reportWebVitals from './reportWebVitals';
import { Provider } from 'react-redux';
import store from './store/index'
const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
    <Provider store={store}>
        <React.StrictMode>
            <Routers />
        </React.StrictMode>
    </Provider>

);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals()

routers/Routers.sx

import { Suspense, lazy } from 'react'
import { BrowserRouter, Routes, Route } from 'react-router-dom' // 使用react-router-dom@6.3.0,和5版本的有很大区别
import App from '../App'
const Home = lazy(() => import('../component/home/Home'))
const User = lazy(() => import('../component/user/User'))

const Routers = () => {
    return <BrowserRouter>
        <Suspense fallback={'...loading'}>
            <Routes>
                <Route path='/' element={<App/>}>
                    <Route path='/' element={<Home/>}/>
                    <Route path='/user' element={<User/>}/>
                </Route>
            </Routes>
        </Suspense>
    </BrowserRouter>
}

export default Routers

以上操作就是react使用ts进行开发的react-redux操作,先看文档,我极力推荐自己的开发可以贴近包推荐的写法进行开发,这样会使你的代码阅读起来更顺畅。

最后也是没办法,但凡我能找到一个能抄的我也不会自己写。