【React】TS项目配置Redux

1 篇文章 0 订阅

前提条件

在React中使用Redux,官方要求安装两个插件,Redux Toolkitreact-redux

Redux Toolkit(RTK): 官方推荐编写Redux逻辑的方式,是一套工具的集合集,简化书写方式

  1. 简化 store 的配置方式
  2. 内置 immer 支持可变式状态修改
  3. 内置 thunk 更好的异步创建

react-redux:用来链接 Redux 和 React组件的中间件。

安装

npm i @reduxjs/toolkit react-redux

浏览器插件 - Redux DevTools(推荐但不强制使用)

下载并启用插件
在这里插入图片描述

控制台找到redux选项
在这里插入图片描述

配置

目录结构

src 下创建 store,其中 index.ts/index.js 作为modules中所有store的集合
在这里插入图片描述

store/index.ts配置

import { configureStore } from '@reduxjs/toolkit'

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

// 后续使用useSelector时参数state的类型
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch

export default store

index.ts 或 main.ts中注册store

import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
// 添加如下
import store from './store'
import { Provider } from 'react-redux'

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

至此已经全局注册了Redux

配置

这里以计数器为例,在store/modules中创建counterSlice.js/ts

同步配置

import { createSlice } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'

export interface CounterState {
  value: number
}

const initialState: CounterState = {
  value: 0,
}


export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: (state:CounterState) => {
      state.value += 1
    },
    decrement: (state:CounterState) => {
      state.value -= 1
    },
  },
})

// 这里的actions对应的是上面的reducers function
export const { increment, decrement } = counterSlice.actions

export default counterSlice.reducer

异步配置

import { createSlice,createAsyncThunk } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'

export interface CounterState {
  value: number
}
const initialState: CounterState = {
  value: 0,
}

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  // 同步操作
  reducers: {
   	......
  },
  // 异步操作
  extraReducers(builder){
    // 这里的payload就是incrementAsync的返回值
    builder.addCase(incrementAsync.fulfilled,(state,{payload})=>{
      state.value += payload
    })
  }
})
// 定义异步函数
export const incrementAsync = createAsyncThunk(
  "incrementAsync",
  async(p:number)=>{
  const res = await new Promise<number>(r=>{
    setTimeout(() => {
      r(p)
    }, 1000);
  })
  return res
})

export const { incrementAsync } = counterSlice.actions

export default counterSlice.reducer

store/index.ts 中注册

import { configureStore } from "@reduxjs/toolkit";
// 引入counterSlice.ts
import counterStore  from "./modules/counterSlice";

const store = configureStore({
  reducer:{
  	// 注册,注意名字要与counterSlice.ts中的name一致
    counter:counterStore
  }
})

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

export default store 

再次查看Redux Tools工具,已经发现value

在这里插入图片描述

使用

// useSelect用于选择操作哪个store
// useDispatch用于生成实例,该实例可以调用reducers的function
import { useSelector, useDispatch } from "react-redux" 

// 引入index中的RootState类型  js项目不需要
import { AppDispatch, RootState } from "@/store" 

// 引入functions
import { decrement, increment, incrementAsync } from "@/store/modules/counterSlice" 

const Demo = () => {
  const count = useSelector((state: RootState) => state.counter.value)
  const dispatch: AppDispatch = useDispatch() // 异步函数必须加AppDispatch类型,否则报错,同步可以不添加
  return (
    <>
      <div className="navbar_top"></div>
      <div>{count}</div>
      <button onClick={() => dispatch(increment())}>+1</button>
      <button onClick={() => dispatch(incrementAsync(2))}>+2</button>
      <button onClick={() => dispatch(decrement())}>-1</button>
    </>
  )
}
export default Demo

操作后通过工具发现value已经改变
在这里插入图片描述

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
React Redux 是一个用于在 React 应用中管理状态的库,而 TypeScript 是一种静态类型检查的编程语言。这两者可以一起使用,以提供类型安全和更好的开发体验。 在使用 React Redux 和 TypeScript 的项目中,你需要安装对应的依赖包,例如 `react-redux` 和 `@types/react-redux`。然后,你可以按照 React Redux 的方式创建和管理状态,并在 TypeScript 中编写相关代码。 下面是一个简单的示例,展示了如何在 React Redux 中使用 TypeScript: ```tsx // MyComponent.tsx import React from "react"; import { useSelector, useDispatch } from "react-redux"; import { RootState, increment, decrement } from "./store"; const MyComponent: React.FC = () => { const counter = useSelector((state: RootState) => state.counter); const dispatch = useDispatch(); return ( <div> <p>Counter: {counter}</p> <button onClick={() => dispatch(increment())}>Increment</button> <button onClick={() => dispatch(decrement())}>Decrement</button> </div> ); }; export default MyComponent; ``` ```tsx // store.ts import { createSlice, configureStore } from "@reduxjs/toolkit"; interface RootState { counter: number; } const initialState: RootState = { counter: 0, }; const counterSlice = createSlice({ name: "counter", initialState, reducers: { increment: (state) => { state.counter++; }, decrement: (state) => { state.counter--; }, }, }); export const { increment, decrement } = counterSlice.actions; export default configureStore({ reducer: { counter: counterSlice.reducer, }, }); ``` 在上述示例中,我们使用 `createSlice` 创建了一个名为 "counter" 的 slice,并定义了两个 action:`increment` 和 `decrement`。我们在组件中使用 `useSelector` 获取状态值,并使用 `useDispatch` 获取 dispatch 函数以触发 action。 这只是一个简单的示例,你可以根据实际需求进行更复杂的状态管理。希望这能帮助到你!如果有更多问题,欢迎继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

田本初

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值