前端
PythonJava运维数据库
状态管理
状态管理
  • 🖥️Redux Tookit
    • Introduction
      • 介绍
    • Tutorials
      • 🖥️快速开始
      • 🏐在TypeScript环境使用
    • Using Redux toolkit
      • 使用Immer编写Reducers
      • 性能与数据范式化
      • 异步逻辑与数据请求
      • Usage With TypeScript
    • API Refrence
      • Store Setup
        • configureStore
        • getDefaultMiddleware
        • Immutability Middleware
        • Serializability Middleware
        • Action Creator Middleware
        • createListenerMiddleware
        • createDynamicMiddleware
        • getDefaultEnhancers
        • autoBatchEnhancer
      • Reducer and Actions
        • createReducer
        • createAction
        • createSlice
        • createAsyncThunk
        • createEntityAdapter
        • combineSlices
      • Other
        • createSelector
        • Matching Utilities
    • RTX Query
      • RTK Query Overview
      • Comparson with Other Tools
      • Examples
      • Usage With TypeScript
      • Using RTK Query
        • Queries
        • Mutations
      • API Refrence
        • createApi
        • fetchBaseQuery
        • ApiProvider
        • setupListeners
        • Generated API Slices
          • Generated API Slices
          • Redux Integration
          • Endpoints
          • Code Splitting
          • Utilities
          • React Hooks
  • 🚚Redux-Saga
    • 入门
    • 基础概念
    • API
    • 技巧
  • 🚑React Redux
    • 安装
    • 教程
    • 使用 React Redux
    • API 参考
  • 🚕生态
    • Redux Persist
    • zustand
      • 使用 useShallow 防止重新渲染
由 GitBook 提供支持
在本页
  • 定义Root State 和 Dispatch 类型
  • 定义Hooks类型
  • 在应用程序中使用
  • 在组件中使用类型钩子

这有帮助吗?

  1. Redux Tookit
  2. Tutorials

在TypeScript环境使用

定义Root State 和 Dispatch 类型

Redux Toolkit configureStore API 不需要任何额外的类型。但是,你需要提取RootState类型和Dispatch类型。以便于根据需要引用他们。

 import { configureStore } from "@reduxjs/toolkit"
 
 const store = configureStore({
   reducer: {}
 })
 
 // 从 store 中推断出 RootState 和 AppDispatch 类型
 export type RootState = ReturnType<typeof store.getSate>
 export type Appdispatch = typeof store.dispatch                                  

定义Hooks类型

尽管你可以将RootState和AppDispatch类型导入每个组件中使用,除此之外,更好的方式时创建useDispatch和useSelector钩子的类型定义。

  • 对于useSelector,它不需要你每次输入(state: RootState)

  • 对于useDispatch:默认的Dispatch类型不知道thunk。为了正确调度thunk,你需要使用store中包含thunk中间件的特定自定义AppDispatch类型,并将其与useDispatch一起使用。添加一个预先输入的useDispatch钩子可以防止你忘记在需要的地方导入Appdispatch。

由于这些是实际变量,而不是类型,因此将它们定义在单独的文件中很重要,而不是store中。这允许你将它们导入到需要使用挂钩的任何组件文件中,并避免潜在的循环导入依赖问题。

import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux"
import type { RootState, AppDispatch } from "./store"

// 在整个应用程序中使用,而不是简单的 useDispatch 和 useSelector
export const useAppDispatch: () => AppDispatch = useDispatch
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector

在应用程序中使用

每个slice文件都应该为其初始state定义一个类型,以便createSlice可以在美中情况下正确推断state的类型reducer。

所有生成的动作都应该使用Redux Toolkit中的PayloadAction类型定义,该类型将action.payload字段的类型作为其通用参数。

import { createSlcie, type PayloadAction } from "@reduxjs/toolkit"
import { type RootState } from "../store"

interface CounterState {
  value: number
}

const initialState: CounterState = {
  value: 0
}

export const counterSlcie = createSlcie({
  name: "counter",
  initialState,
  reducers: {
    increment: state => {
      state.value += 1
    },
    decrement: state => {
      state.value -= 1
    },
    incrementByAmount: (state, action: PayloadAction<number>) => {
      state.value += action.paylaod
    }
  }
})

export const { increment, decrement, incrementByAmount } = counterSlice.actions
export const selectSounter = (state: RootState) => state.counter.value
export default counterSlcie.reducer

在组件中使用类型钩子

import React from "react"
import { useAppSelector, useAppDispatch } from "../../app/hooks"

import { decrement, increment } from "./counterSlice"
export function counter() {
  const count = useAppSelector(state => state.counter.value)
  const appDispatch = useAppDispatch()
}
上一页快速开始下一页Using Redux toolkit

最后更新于9个月前

这有帮助吗?

🖥️
🏐