Setup > Migrating to Modern Redux: how to modernize legacy Redux code">Setup > Migrating to Modern Redux: how to modernize legacy Redux code">
跳至主要内容

迁移到现代 Redux

你将学到什么
  • 如何将传统的“手写”Redux 逻辑现代化,以使用 Redux Toolkit
  • 如何将传统的 React-Redux connect 组件现代化为使用 hooks API
  • 如何将使用 TypeScript 的 Redux 逻辑和 React-Redux 组件现代化

概述

Redux 自 2015 年问世以来,我们编写 Redux 代码的推荐模式已经发生了重大变化。就像 React 从 createClass 演变到 React.Component 再到带有 hooks 的函数组件一样,Redux 也从手动商店设置 + 手写 reducer(使用对象扩展) + React-Redux 的 connect 演变到 Redux Toolkit 的 configureStore + createSlice + React-Redux 的 hooks API。

许多用户正在使用比这些“现代 Redux”模式出现更早的 Redux 代码库。将这些代码库迁移到当今推荐的现代 Redux 模式将导致代码库更小,更容易维护。

好消息是,您可以逐步地、逐段地将代码迁移到现代 Redux,旧的和新的 Redux 代码可以共存并协同工作!

本页介绍了用于现代化现有传统 Redux 代码库的通用方法和技术。

信息

有关使用 Redux Toolkit + React-Redux hooks 的“现代 Redux”如何简化 Redux 使用的更多详细信息,请参阅以下其他资源

使用 Redux Toolkit 现代化 Redux 逻辑

迁移 Redux 逻辑的通用方法是

  • 用 Redux Toolkit 的 configureStore 替换现有的手动 Redux 商店设置
  • 选择一个现有的切片 reducer 和其关联的动作。用 RTK 的 createSlice 替换它们。一次替换一个 reducer。
  • 根据需要,用 RTK Query 或 createAsyncThunk 替换现有的数据获取逻辑
  • 根据需要使用 RTK 的其他 API,例如 createListenerMiddlewarecreateEntityAdapter

你应该始终从用 configureStore 替换传统的 createStore 调用开始。这是一个一次性步骤,所有现有的 reducer 和中间件将继续按原样工作。configureStore 包含开发模式检查,用于检查常见的错误,例如意外的变异和不可序列化的值,因此拥有这些检查将有助于识别代码库中发生这些错误的任何区域。

信息

你可以在 Redux 基础知识,第 8 部分:使用 Redux Toolkit 的现代 Redux 中看到这种通用方法的实际应用。

使用 configureStore 设置存储

一个典型的传统 Redux 存储设置文件执行几个不同的步骤

  • 将切片 reducer 组合成根 reducer
  • 创建中间件增强器,通常使用 thunk 中间件,以及可能在开发模式下的其他中间件,例如 redux-logger
  • 添加 Redux DevTools 增强器,并将增强器组合在一起
  • 调用 createStore

以下是这些步骤在现有应用程序中的可能样子

src/app/store.js
import { createStore, applyMiddleware, combineReducers, compose } from 'redux'
import thunk from 'redux-thunk'

import postsReducer from '../reducers/postsReducer'
import usersReducer from '../reducers/usersReducer'

const rootReducer = combineReducers({
posts: postsReducer,
users: usersReducer
})

const middlewareEnhancer = applyMiddleware(thunk)

const composeWithDevTools =
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose

const composedEnhancers = composeWithDevTools(middlewareEnhancer)

const store = createStore(rootReducer, composedEnhancers)

所有这些步骤都可以用对 Redux Toolkit 的 configureStore API 的一次调用来替换.

RTK 的 configureStore 围绕原始的 createStore 方法进行包装,并自动为我们处理大多数存储设置。实际上,我们可以将其简化为有效的一步

基本存储设置:src/app/store.js
import { configureStore } from '@reduxjs/toolkit'

import postsReducer from '../reducers/postsReducer'
import usersReducer from '../reducers/usersReducer'

// Automatically adds the thunk middleware and the Redux DevTools extension
const store = configureStore({
// Automatically calls `combineReducers`
reducer: {
posts: postsReducer,
users: usersReducer
}
})

configureStore 的一次调用就完成了所有工作

  • 它调用了 combineReducerspostsReducerusersReducer 组合成根 reducer 函数,该函数将处理看起来像 {posts, users} 的根状态
  • 它调用了 createStore 使用该根 reducer 创建 Redux 存储
  • 它自动添加了 thunk 中间件并调用了 applyMiddleware
  • 它自动添加了更多中间件来检查常见的错误,例如意外地修改状态
  • 它自动设置了 Redux DevTools 扩展连接

如果您的商店设置需要额外的步骤,例如添加额外的中间件,向 thunk 中间件传递 extra 参数,或创建一个持久化的根 reducer,您也可以这样做。以下是一个更大的示例,展示了自定义内置中间件和启用 Redux-Persist,它演示了一些使用 configureStore 的选项。

详细示例:带有持久性和中间件的自定义商店设置

此示例展示了在设置 Redux 商店时可能遇到的几种常见任务。

  • 单独组合 reducer(有时由于其他架构约束而需要)。
  • 添加额外的中间件,有条件地和无条件地。
  • 将“额外参数”传递到 thunk 中间件,例如 API 服务层。
  • 使用 Redux-Persist 库,它需要对不可序列化的动作类型进行特殊处理。
  • 在生产环境中关闭 devtools,并在开发环境中设置额外的 devtools 选项。

这些都不是必需的,但它们确实经常出现在现实世界的代码库中。

自定义商店设置:src/app/store.js
import { configureStore, combineReducers } from '@reduxjs/toolkit'
import {
persistStore,
persistReducer,
FLUSH,
REHYDRATE,
PAUSE,
PERSIST,
PURGE,
REGISTER
} from 'redux-persist'
import storage from 'redux-persist/lib/storage'
import { PersistGate } from 'redux-persist/integration/react'
import logger from 'redux-logger'

import postsReducer from '../features/posts/postsSlice'
import usersReducer from '../features/users/usersSlice'
import { api } from '../features/api/apiSlice'
import { serviceLayer } from '../features/api/serviceLayer'

import stateSanitizerForDevtools from './devtools'
import customMiddleware from './someCustomMiddleware'

// Can call `combineReducers` yourself if needed
const rootReducer = combineReducers({
posts: postsReducer,
users: usersReducer,
[api.reducerPath]: api.reducer
})

const persistConfig = {
key: 'root',
version: 1,
storage
}

const persistedReducer = persistReducer(persistConfig, rootReducer)

const store = configureStore({
// Pass previously created persisted reducer
reducer: persistedReducer,
middleware: getDefaultMiddleware => {
const middleware = getDefaultMiddleware({
// Pass in a custom `extra` argument to the thunk middleware
thunk: {
extraArgument: { serviceLayer }
},
// Customize the built-in serializability dev check
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER]
}
}).concat(customMiddleware, api.middleware)

// Conditionally add another middleware in dev
if (process.env.NODE_ENV !== 'production') {
middleware.push(logger)
}

return middleware
},
// Turn off devtools in prod, or pass options in dev
devTools:
process.env.NODE_ENV === 'production'
? false
: {
stateSanitizer: stateSanitizerForDevtools
}
})

使用 createSlice 的 Reducer 和 Action

典型的传统 Redux 代码库将其 reducer 逻辑、动作创建者和动作类型分散在不同的文件中,这些文件通常按类型位于不同的文件夹中。reducer 逻辑使用 switch 语句和手动编写的不可变更新逻辑(使用对象扩展和数组映射)编写。

src/constants/todos.js
export const ADD_TODO = 'ADD_TODO'
export const TOGGLE_TODO = 'TOGGLE_TODO'
src/actions/todos.js
import { ADD_TODO, TOGGLE_TODO } from '../constants/todos'

export const addTodo = (id, text) => ({
type: ADD_TODO,
text,
id
})

export const toggleTodo = id => ({
type: TOGGLE_TODO,
id
})
src/reducers/todos.js
import { ADD_TODO, TOGGLE_TODO } from '../constants/todos'

const initialState = []

export default function todosReducer(state = initialState, action) {
switch (action.type) {
case ADD_TODO: {
return state.concat({
id: action.id,
text: action.text,
completed: false
})
}
case TOGGLE_TODO: {
return state.map(todo => {
if (todo.id !== action.id) {
return todo
}

return {
...todo,
completed: !todo.completed
}
})
}
default:
return state
}
}

Redux Toolkit 的 createSlice API 旨在消除编写 reducer、动作和不可变更新的所有“样板代码”!

使用 Redux Toolkit,对传统代码进行了多项更改。

  • createSlice 将完全消除手动编写的动作创建者和动作类型。
  • 所有唯一命名的字段,如 action.textaction.id,都将被 action.payload 替换,可以是单个值,也可以是包含这些字段的对象。
  • 手动编写的不可变更新被 reducer 中的“可变”逻辑替换,这得益于 Immer。
  • 不需要为每种类型的代码创建单独的文件。
  • 我们建议将给定 reducer 的所有逻辑都放在一个“切片”文件中。
  • 我们建议不要按“代码类型”创建单独的文件夹,而是按“功能”组织文件,将相关代码放在同一个文件夹中。
  • 理想情况下,reducer 和 action 的命名应该使用过去式,描述“发生的事情”,而不是命令式的“现在做这件事”,例如 todoAdded 而不是 ADD_TODO

这些用于常量、action 和 reducer 的单独文件将全部替换为单个“slice”文件。现代化的 slice 文件看起来像这样

src/features/todos/todosSlice.js
import { createSlice } from '@reduxjs/toolkit'

const initialState = []

const todosSlice = createSlice({
name: 'todos',
initialState,
reducers: {
// Give case reducers meaningful past-tense "event"-style names
todoAdded(state, action) {
const { id, text } = action.payload
// "Mutating" update syntax thanks to Immer, and no `return` needed
state.todos.push({
id,
text,
completed: false
})
},
todoToggled(state, action) {
// Look for the specific nested object to update.
// In this case, `action.payload` is the default field in the action,
// and can hold the `id` value - no need for `action.id` separately
const matchingTodo = state.todos.find(todo => todo.id === action.payload)

if (matchingTodo) {
// Can directly "mutate" the nested object
matchingTodo.completed = !matchingTodo.completed
}
}
}
})

// `createSlice` automatically generated action creators with these names.
// export them as named exports from this "slice" file
export const { todoAdded, todoToggled } = todosSlice.actions

// Export the slice reducer as the default export
export default todosSlice.reducer

当您调用 dispatch(todoAdded('Buy milk')) 时,您传递给 todoAdded action creator 的任何单个值都会自动用作 action.payload 字段。如果您需要传递多个值,请以对象的形式传递,例如 dispatch(todoAdded({id, text}))。或者,您可以使用 createSlice reducer 中的“prepare”符号 来接受多个单独的参数并创建 payload 字段。prepare 符号对于 action creator 执行额外工作的情况也很有用,例如为每个项目生成唯一的 ID。

虽然 Redux Toolkit 不特别关心您的文件夹和文件结构或 action 命名,但 我们推荐这些最佳实践,因为我们发现它们可以带来更易于维护和理解的代码。

使用 RTK Query 进行数据获取

典型的 React+Redux 应用程序中的传统数据获取需要许多移动部件和代码类型

  • 表示“请求开始”、“请求成功”和“请求失败”操作的 action creator 和 action 类型
  • 用于调度 action 并发出异步请求的 thunk
  • 跟踪加载状态并存储缓存数据的 reducer
  • 用于从存储中读取这些值的 selector
  • 在组件挂载后调度 thunk,无论是通过类组件中的 componentDidMount 还是函数组件中的 useEffect

这些通常会分布在许多不同的文件中

src/constants/todos.js
export const FETCH_TODOS_STARTED = 'FETCH_TODOS_STARTED'
export const FETCH_TODOS_SUCCEEDED = 'FETCH_TODOS_SUCCEEDED'
export const FETCH_TODOS_FAILED = 'FETCH_TODOS_FAILED'
src/actions/todos.js
import axios from 'axios'
import {
FETCH_TODOS_STARTED,
FETCH_TODOS_SUCCEEDED,
FETCH_TODOS_FAILED
} from '../constants/todos'

export const fetchTodosStarted = () => ({
type: FETCH_TODOS_STARTED
})

export const fetchTodosSucceeded = todos => ({
type: FETCH_TODOS_SUCCEEDED,
todos
})

export const fetchTodosFailed = error => ({
type: FETCH_TODOS_FAILED,
error
})

export const fetchTodos = () => {
return async dispatch => {
dispatch(fetchTodosStarted())

try {
// Axios is common, but also `fetch`, or your own "API service" layer
const res = await axios.get('/todos')
dispatch(fetchTodosSucceeded(res.data))
} catch (err) {
dispatch(fetchTodosFailed(err))
}
}
}
src/reducers/todos.js
import {
FETCH_TODOS_STARTED,
FETCH_TODOS_SUCCEEDED,
FETCH_TODOS_FAILED
} from '../constants/todos'

const initialState = {
status: 'uninitialized',
todos: [],
error: null
}

export default function todosReducer(state = initialState, action) {
switch (action.type) {
case FETCH_TODOS_STARTED: {
return {
...state,
status: 'loading'
}
}
case FETCH_TODOS_SUCCEEDED: {
return {
...state,
status: 'succeeded',
todos: action.todos
}
}
case FETCH_TODOS_FAILED: {
return {
...state,
status: 'failed',
todos: [],
error: action.error
}
}
default:
return state
}
}
src/selectors/todos.js
export const selectTodosStatus = state => state.todos.status
export const selectTodos = state => state.todos.todos
src/components/TodosList.js
import { useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { fetchTodos } from '../actions/todos'
import { selectTodosStatus, selectTodos } from '../selectors/todos'

export function TodosList() {
const dispatch = useDispatch()
const status = useSelector(selectTodosStatus)
const todos = useSelector(selectTodos)

useEffect(() => {
dispatch(fetchTodos())
}, [dispatch])

// omit rendering logic here
}

许多用户可能正在使用redux-saga库来管理数据获取,在这种情况下,他们可能拥有额外的“信号”动作类型来触发saga,以及这个saga文件而不是thunk

src/sagas/todos.js
import { put, takeEvery, call } from 'redux-saga/effects'
import {
FETCH_TODOS_BEGIN,
fetchTodosStarted,
fetchTodosSucceeded,
fetchTodosFailed
} from '../actions/todos'

// Saga to actually fetch data
export function* fetchTodos() {
yield put(fetchTodosStarted())

try {
const res = yield call(axios.get, '/todos')
yield put(fetchTodosSucceeded(res.data))
} catch (err) {
yield put(fetchTodosFailed(err))
}
}

// "Watcher" saga that waits for a "signal" action, which is
// dispatched only to kick off logic, not to update state
export function* fetchTodosSaga() {
yield takeEvery(FETCH_TODOS_BEGIN, fetchTodos)
}

所有这些代码都可以用Redux Toolkit 的“RTK Query”数据获取和缓存层替换!

RTK Query 替代了编写任何动作、thunk、reducer、selector 或 effect 来管理数据获取的需要。(事实上,它实际上使用了所有这些相同的工具。)此外,RTK Query 负责跟踪加载状态、对请求进行去重以及管理缓存数据生命周期(包括删除不再需要的过期数据)。

要迁移,设置一个单独的 RTK Query “API 切片”定义,并将生成的 reducer + 中间件添加到您的商店

src/features/api/apiSlice.js
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

export const api = createApi({
baseQuery: fetchBaseQuery({
// Fill in your own server starting URL here
baseUrl: '/'
}),
endpoints: build => ({})
})
src/app/store.js
import { configureStore } from '@reduxjs/toolkit'

// Import the API object
import { api } from '../features/api/apiSlice'
// Import any other slice reducers as usual here
import usersReducer from '../features/users/usersSlice'

export const store = configureStore({
reducer: {
// Add the generated RTK Query "API slice" caching reducer
[api.reducerPath]: api.reducer,
// Add any other reducers
users: usersReducer
},
// Add the RTK Query API middleware
middleware: getDefaultMiddleware =>
getDefaultMiddleware().concat(api.middleware)
})

然后,添加表示您想要获取和缓存的特定数据的“端点”,并导出每个端点的自动生成的 React hook

src/features/api/apiSlice.js
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

export const api = createApi({
baseQuery: fetchBaseQuery({
// Fill in your own server starting URL here
baseUrl: '/'
}),
endpoints: build => ({
// A query endpoint with no arguments
getTodos: build.query({
query: () => '/todos'
}),
// A query endpoint with an argument
userById: build.query({
query: userId => `/users/${userId}`
}),
// A mutation endpoint
updateTodo: build.mutation({
query: updatedTodo => ({
url: `/todos/${updatedTodo.id}`,
method: 'POST',
body: updatedTodo
})
})
})
})

export const { useGetTodosQuery, useUserByIdQuery, useUpdateTodoMutation } = api

最后,在您的组件中使用这些 hook

src/features/todos/TodoList.js
import { useGetTodosQuery } from '../api/apiSlice'

export function TodoList() {
const { data: todos, isFetching, isSuccess } = useGetTodosQuery()

// omit rendering logic here
}

使用createAsyncThunk进行数据获取

我们特别建议使用 RTK Query 进行数据获取。但是,一些用户告诉我们他们还没有准备好迈出这一步。在这种情况下,您至少可以减少使用 RTK 的createAsyncThunk手写 thunk 和 reducer 的一些样板代码。它会自动为您生成动作创建者和动作类型,调用您提供的异步函数来发出请求,并根据 promise 生命周期调度这些动作。使用createAsyncThunk的相同示例可能如下所示

src/features/todos/todosSlice
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import axios from 'axios'

const initialState = {
status: 'uninitialized',
todos: [],
error: null
}

const fetchTodos = createAsyncThunk('todos/fetchTodos', async () => {
// Just make the async request here, and return the response.
// This will automatically dispatch a `pending` action first,
// and then `fulfilled` or `rejected` actions based on the promise.
// as needed based on the
const res = await axios.get('/todos')
return res.data
})

export const todosSlice = createSlice({
name: 'todos',
initialState,
reducers: {
// any additional "normal" case reducers here.
// these will generate new action creators
},
extraReducers: builder => {
// Use `extraReducers` to handle actions that were generated
// _outside_ of the slice, such as thunks or in other slices
builder
.addCase(fetchTodos.pending, (state, action) => {
state.status = 'loading'
})
// Pass the generated action creators to `.addCase()`
.addCase(fetchTodos.fulfilled, (state, action) => {
// Same "mutating" update syntax thanks to Immer
state.status = 'succeeded'
state.todos = action.payload
})
.addCase(fetchTodos.rejected, (state, action) => {
state.status = 'failed'
state.todos = []
state.error = action.error
})
}
})

export default todosSlice.reducer

您还需要编写任何 selector,并在useEffect hook 中自己调度fetchTodos thunk。

使用createListenerMiddleware进行响应式逻辑

许多 Redux 应用程序具有“响应式”逻辑,该逻辑监听特定动作或状态更改,并响应运行其他逻辑。这些行为通常使用redux-sagaredux-observable库实现。

这些库用于各种各样的任务。作为一个基本示例,一个监听动作、等待一秒钟,然后调度额外动作的 saga 和 epic 可能如下所示

src/sagas/ping.js
import { delay, put, takeEvery } from 'redux-saga/effects'

export function* ping() {
yield delay(1000)
yield put({ type: 'PONG' })
}

// "Watcher" saga that waits for a "signal" action, which is
// dispatched only to kick off logic, not to update state
export function* pingSaga() {
yield takeEvery('PING', ping)
}
src/epics/ping.js
import { filter, mapTo } from 'rxjs/operators'
import { ofType } from 'redux-observable'

const pingEpic = action$ =>
action$.pipe(ofType('PING'), delay(1000), mapTo({ type: 'PONG' }))
src/app/store.js
import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga'
import { combineEpics, createEpicMiddleware } from 'redux-observable';

// skip reducers

import { pingEpic } from '../sagas/ping'
import { pingSaga } from '../epics/ping

function* rootSaga() {
yield pingSaga()
}

const rootEpic = combineEpics(
pingEpic
);

const sagaMiddleware = createSagaMiddleware()
const epicMiddleware = createEpicMiddleware()

const middlewareEnhancer = applyMiddleware(sagaMiddleware, epicMiddleware)

const store = createStore(rootReducer, middlewareEnhancer)

sagaMiddleware.run(rootSaga)
epicMiddleware.run(rootEpic)

RTK “监听器”中间件旨在用更简单的 API、更小的包大小和更好的 TS 支持来替换 saga 和 observable。

saga 和 epic 示例可以用监听器中间件替换,如下所示

src/app/listenerMiddleware.js
import { createListenerMiddleware } from '@reduxjs/toolkit'

// Best to define this in a separate file, to avoid importing
// from the store file into the rest of the codebase
export const listenerMiddleware = createListenerMiddleware()

export const { startListening, stopListening } = listenerMiddleware
src/features/ping/pingSlice.js
import { createSlice } from '@reduxjs/toolkit'
import { startListening } from '../../app/listenerMiddleware'

const pingSlice = createSlice({
name: 'ping',
initialState,
reducers: {
pong(state, action) {
// state update here
}
}
})

export const { pong } = pingSlice.actions
export default pingSlice.reducer

// The `startListening()` call could go in different files,
// depending on your preferred app setup. Here, we just add
// it directly in a slice file.
startListening({
// Match this exact action type based on the action creator
actionCreator: pong,
// Run this effect callback whenever that action is dispatched
effect: async (action, listenerApi) => {
// Listener effect functions get a `listenerApi` object
// with many useful methods built in, including `delay`:
await listenerApi.delay(1000)
listenerApi.dispatch(pong())
}
})
src/app/store.js
import { configureStore } from '@reduxjs/toolkit'

import { listenerMiddleware } from './listenerMiddleware'

// omit reducers

export const store = configureStore({
reducer: rootReducer,
// Add the listener middleware _before_ the thunk or dev checks
middleware: getDefaultMiddleware =>
getDefaultMiddleware().prepend(listenerMiddleware.middleware)
})

迁移 Redux Logic 的 TypeScript

使用 TypeScript 的传统 Redux 代码通常遵循非常冗长的类型定义模式。特别是,社区中的许多用户决定为每个单独的动作手动定义 TS 类型,然后创建“动作类型联合”,试图限制实际可以传递给dispatch的特定动作。

我们明确强烈建议反对这些模式!

src/actions/todos.ts
import { ADD_TODO, TOGGLE_TODO } from '../constants/todos'

// ❌ Common pattern: manually defining types for each action object
interface AddTodoAction {
type: typeof ADD_TODO
text: string
id: string
}

interface ToggleTodoAction {
type: typeof TOGGLE_TODO
id: string
}

// ❌ Common pattern: an "action type union" of all possible actions
export type TodoActions = AddTodoAction | ToggleTodoAction

export const addTodo = (id: string, text: string): AddTodoAction => ({
type: ADD_TODO,
text,
id
})

export const toggleTodo = (id: string): ToggleTodoAction => ({
type: TOGGLE_TODO,
id
})
src/reducers/todos.ts
import { ADD_TODO, TOGGLE_TODO, TodoActions } from '../constants/todos'

interface Todo {
id: string
text: string
completed: boolean
}

export type TodosState = Todo[]

const initialState: TodosState = []

export default function todosReducer(
state = initialState,
action: TodoActions
) {
switch (action.type) {
// omit reducer logic
default:
return state
}
}
src/app/store.ts
import { createStore, Dispatch } from 'redux'

import { TodoActions } from '../actions/todos'
import { CounterActions } from '../actions/counter'
import { TodosState } from '../reducers/todos'
import { CounterState } from '../reducers/counter'

// omit reducer setup

export const store = createStore(rootReducer)

// ❌ Common pattern: an "action type union" of all possible actions
export type RootAction = TodoActions | CounterActions
// ❌ Common pattern: manually defining the root state type with each field
export interface RootState {
todos: TodosState
counter: CounterState
}

// ❌ Common pattern: limiting what can be dispatched at the types level
export type AppDispatch = Dispatch<RootAction>

Redux Toolkit 旨在极大地简化 TS 的使用,我们的建议包括尽可能推断类型!

根据我们的标准 TypeScript 设置和使用指南,从设置存储文件开始,直接从存储本身推断AppDispatchRootState类型。这将正确地包含由中间件添加的任何对dispatch的修改,例如调度 thunk 的能力,并在您修改切片的 state 定义或添加更多切片时更新RootState类型。

app/store.ts
import { configureStore } from '@reduxjs/toolkit'
// omit any other imports

const store = configureStore({
reducer: {
todos: todosReducer,
counter: counterReducer
}
})

// Infer the `RootState` and `AppDispatch` types from the store itself

// Inferred state type: {todos: TodosState, counter: CounterState}
export type RootState = ReturnType<typeof store.getState>

// Inferred dispatch type: Dispatch & ThunkDispatch<RootState, undefined, UnknownAction>
export type AppDispatch = typeof store.dispatch

每个切片文件都应该声明并导出其自身切片 state 的类型。然后,使用PayloadAction类型来声明createSlice.reducers中任何action参数的类型。生成的 action 创建者也将具有它们接受的参数的正确类型,以及它们返回的action.payload的类型。

src/features/todos/todosSlice.ts
import { createSlice, PayloadAction } from '@reduxjs/toolkit'

interface Todo {
id: string
text: string
completed: boolean
}

// Declare and export a type for the slice's state
export type TodosState = Todo[]

const initialState: TodosState = []

const todosSlice = createSlice({
name: 'todos',
// The `state` argument type will be inferred for all case reducers
// from the type of `initialState`
initialState,
reducers: {
// Use `PayloadAction<YourPayloadTypeHere>` for each `action` argument
todoAdded(state, action: PayloadAction<{ id: string; text: string }>) {
// omit logic
},
todoToggled(state, action: PayloadAction<string>) {
// omit logic
}
}
})

使用 React-Redux 现代化 React 组件

在组件中迁移 React-Redux 使用的一般方法是

  • 将现有的 React 类组件迁移为函数组件
  • useSelectoruseDispatch钩子的使用替换connect包装器组件内部

您可以逐个组件地执行此操作。使用connect和钩子的组件可以同时共存。

本页面不会涵盖将类组件迁移到函数组件的过程,而是会重点介绍 React-Redux 的特定更改。

connect 迁移到 Hooks

一个典型的使用 React-Redux 的 connect API 的传统组件可能如下所示

src/features/todos/TodoListItem.js
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import {
todoToggled,
todoDeleted,
selectTodoById,
selectActiveTodoId
} from './todosSlice'

// A `mapState` function, possibly using values from `ownProps`,
// and returning an object with multiple separate fields inside
const mapStateToProps = (state, ownProps) => {
return {
todo: selectTodoById(state, ownProps.todoId),
activeTodoId: selectActiveTodoId(state)
}
}

// Several possible variations on how you might see `mapDispatch` written:

// 1) a separate function, manual wrapping of `dispatch`
const mapDispatchToProps = dispatch => {
return {
todoDeleted: id => dispatch(todoDeleted(id)),
todoToggled: id => dispatch(todoToggled(id))
}
}

// 2) A separate function, wrapping with `bindActionCreators`
const mapDispatchToProps2 = dispatch => {
return bindActionCreators(
{
todoDeleted,
todoToggled
},
dispatch
)
}

// 3) An object full of action creators
const mapDispatchToProps3 = {
todoDeleted,
todoToggled
}

// The component, which gets all these fields as props
function TodoListItem({ todo, activeTodoId, todoDeleted, todoToggled }) {
// rendering logic here
}

// Finished with the call to `connect`
export default connect(mapStateToProps, mapDispatchToProps)(TodoListItem)

使用 React-Redux hooks API,connect 调用和 mapState/mapDispatch 参数将被 hooks 替换!

  • mapState 中返回的每个单独字段都将成为一个单独的 useSelector 调用
  • 通过 mapDispatch 传递的每个函数都将成为组件内部定义的单独回调函数
src/features/todos/TodoListItem.js
import { useState } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import {
todoAdded,
todoToggled,
selectTodoById,
selectActiveTodoId
} from './todosSlice'

export function TodoListItem({ todoId }) {
// Get the actual `dispatch` function with `useDispatch`
const dispatch = useDispatch()

// Select values from the state with `useSelector`
const activeTodoId = useSelector(selectActiveTodoId)
// Use prop in scope to select a specific value
const todo = useSelector(state => selectTodoById(state, todoId))

// Create callback functions that dispatch as needed, with arguments
const handleToggleClick = () => {
dispatch(todoToggled(todoId))
}

const handleDeleteClick = () => {
dispatch(todoDeleted(todoId))
}

// omit rendering logic
}

有一点不同的是,connect 通过阻止包装组件渲染来优化渲染性能,除非其传入的 stateProps+dispatchProps+ownProps 已更改。hooks 无法做到这一点,因为它们位于组件内部。如果您需要阻止 React 的正常递归渲染行为,请自己将组件包装在 React.memo(MyComponent) 中。

迁移组件的 TypeScript

connect 的主要缺点之一是它非常难以正确类型化,并且类型声明最终会变得非常冗长。这是因为它是一个高阶组件,以及其 API 的灵活性(四个参数,全部可选,每个参数都有多个可能的重载和变体)。

社区提出了多种处理此问题的变体,复杂程度各不相同。在低端,一些用法需要在 mapState() 中对 state 进行类型化,然后计算组件的所有 props 的类型

简单的 connect TS 示例
import { connect } from 'react-redux'
import { RootState } from '../../app/store'
import {
todoToggled,
todoDeleted,
selectTodoById,
selectActiveTodoId
} from './todosSlice'

interface TodoListItemOwnProps {
todoId: string
}

const mapStateToProps = (state: RootState, ownProps) => {
return {
todo: selectTodoById(state, ownProps.todoId),
activeTodoId: selectActiveTodoId(state)
}
}

const mapDispatchToProps = {
todoDeleted,
todoToggled
}

type TodoListItemProps = TodoListItemOwnProps &
ReturnType<typeof mapStateToProps> &
typeof mapDispatchToProps

function TodoListItem({
todo,
activeTodoId,
todoDeleted,
todoToggled
}: TodoListItemProps) {}

export default connect(mapStateToProps, mapDispatchToProps)(TodoListItem)

特别是将 typeof mapDispatch 用作对象很危险,因为它会在包含 thunk 时失败。

其他社区创建的模式需要明显更多的开销,包括将 mapDispatch 声明为函数并在其中调用 bindActionCreators 以传递 dispatch: Dispatch<RootActions> 类型,或者手动计算包装组件接收到的所有 props 的类型,并将这些类型作为泛型传递给 connect

一个稍微好一点的替代方案是 `ConnectedProps<T>` 类型,它在 v7.x 版本中被添加到 `@types/react-redux` 中,它可以推断出从 `connect` 传递给组件的所有 props 的类型。这确实需要将对 `connect` 的调用拆分为两个部分,才能使推断正常工作。

ConnectedProps<T> TS 示例
import { connect, ConnectedProps } from 'react-redux'
import { RootState } from '../../app/store'
import {
todoToggled,
todoDeleted,
selectTodoById,
selectActiveTodoId
} from './todosSlice'

interface TodoListItemOwnProps {
todoId: string
}

const mapStateToProps = (state: RootState, ownProps) => {
return {
todo: selectTodoById(state, ownProps.todoId),
activeTodoId: selectActiveTodoId(state)
}
}

const mapDispatchToProps = {
todoDeleted,
todoToggled
}

// Call the first part of `connect` to get the function that accepts the component.
// This knows the types of the props returned by `mapState/mapDispatch`
const connector = connect(mapStateToProps, mapDispatchToProps)
// The `ConnectedProps<T> util type can extract "the type of all props from Redux"
type PropsFromRedux = ConnectedProps<typeof connector>

// The final component props are "the props from Redux" + "props from the parent"
type TodoListItemProps = PropsFromRedux & TodoListItemOwnProps

// That type can then be used in the component
function TodoListItem({
todo,
activeTodoId,
todoDeleted,
todoToggled
}: TodoListItemProps) {}

// And the final wrapped component is generated and exported
export default connector(TodoListItem)

React-Redux hooks API 在 TypeScript 中使用起来非常简单! 与处理组件包装层、类型推断和泛型不同,hooks 是简单的函数,它们接受参数并返回结果。您只需要传递 `RootState` 和 `AppDispatch` 的类型。

根据 我们标准的 TypeScript 设置和使用指南,我们专门教授为 hooks 设置“预先类型化”的别名,以便它们具有正确的类型,并且只在应用程序中使用这些预先类型化的 hooks。

首先,设置 hooks

src/app/hooks.ts
import { useDispatch, useSelector } from 'react-redux'
import type { AppDispatch, RootState } from './store'

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = useDispatch.withTypes<AppDispatch>()
export const useAppSelector = useSelector.withTypes<RootState>()

然后,在您的组件中使用它们

src/features/todos/TodoListItem.tsx
import { useAppSelector, useAppDispatch } from '../../app/hooks'
import {
todoToggled,
todoDeleted,
selectTodoById,
selectActiveTodoId
} from './todosSlice'

interface TodoListItemProps {
todoId: string
}

function TodoListItem({ todoId }: TodoListItemProps) {
// Use the pre-typed hooks in the component
const dispatch = useAppDispatch()
const activeTodoId = useAppSelector(selectActiveTodoId)
const todo = useAppSelector(state => selectTodoById(state, todoId))

// omit event handlers and rendering logic
}

更多信息

请查看这些文档页面和博客文章以了解更多详细信息