redux/toolkit
- configureStroe
configureStroe 建立一个store,包括reducers以及thunk 中间件,并且连接redux DevTools等工作。 总之就是把使用原生的redux,原来一些需要手动写的代码,自动给你封装起来。
configureStore sets up a well-configured Redux store with a single function call, including combining reducers, adding the thunk middleware, and setting up the Redux DevTools integration. It also is easier to configure than createStore, because it takes named options parameters.
- createSlice
createSlice 可以写一个reducers,并且已经集成了Immer,可以让你放心的修改state。
同时可以自动生成actions,并且很好的支持Typescript
createSlice lets you write reducers that use the Immer library to enable writing immutable updates using "mutating" JS syntax like state.value = 123, with no spreads needed. It also automatically generates action creator functions for each reducer, and generates action type strings internally based on your reducer's names. Finally, it works great with TypeScript.
比如现在写redux,就变成这样
// features/todos/todosSlice.js
import { createSlice } from '@reduxjs/toolkit'
const todosSlice = createSlice({
name: 'todos',
initialState: [],
reducers: {
todoAdded(state, action) {
state.push({
id: action.payload.id,
text: action.payload.text,
completed: false
})
},
todoToggled(state, action) {
const todo = state.find(todo => todo.id === action.payload)
todo.completed = !todo.completed
}
}
})
export const { todoAdded, todoToggled } = todosSlice.actions
export default todosSlice.reducer
然后使用configureStore连接起来就可以了
import { configureStore } from '@reduxjs/toolkit'
import todosReducer from '../features/todos/todosSlice'
import filtersReducer from '../features/filters/filtersSlice'
export const store = configureStore({
reducer: {
todos: todosReducer,
filters: filtersReducer
}
})
configureStore 做了几件工作,主要是合并reducers,绑定redux-thunk等。
- The slice reducers were automatically passed to combineReducers()
- The redux-thunk middleware was automatically added Dev-mode middleware was added to catch accidental mutations
- The Redux DevTools Extension was automatically set up
- The middleware and DevTools enhancers were composed together and added to the store
最后,redux/toolkit同时也自动引入了RTK Query(主要是用于请求接口)
- 为什么需要使用redux/toolkit
主要是它可以让你写更少的代码,并且帮助你避免一些常见的错误等;
We want all Redux users to write their Redux code with Redux Toolkit, because it simplifies your code and eliminates many common Redux mistakes and bugs!