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
尽管你可以将RootState和AppDispatch类型导入每个组件中使用,除此之外,更好的方式时创建useDispatch和useSelector钩子的类型定义。
由于这些是实际变量,而不是类型,因此将它们定义在单独的文件中很重要,而不是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
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()
}