状态管理工具,redux的最佳使用方式,是简易的,高效的
Redux Toolkit 包含:
1.configureStore()
封装了createStore,简化配置,提供默认配置项,组合切片的reducer
2.createReducer()
将 action 类型映射到reducer函数,自动调用immer库将可变代码编写更简单的不可变更新
3.createAction()
根据 action 类型生成 action 函数,本身有tostring(),可以替代常量使用
4.createSlice()
接收一组 reducer 函数的对象,一个 slice 切片名和初始状态 initial state,并自动生成具有相应 action creator 和 action type 的 slice reducer。
5.createAsyncThunk() (异步)
接收一个 action type 字符串和一个返回值为 promise 的函数, 并生成一个 thunk 函数,这个 thunk 函数可以基于之前那个 promise ,dispatch 一组 type 为 promise 状态类型 的 action。
6.createEntityAdapter()
生成一系列可复用的 reducer 和 selector,从而管理 store 中的规范化数据。
7.createSelector()
来源来源于 Reselect 库,重新 export 出来以方便使用
创建 Redux Store
创建src/store/index.js文件夹,
import { configureStore } from '@reduxjs/toolkit'
export const store=configureStore({
reducer:{}
})
在入口文件里面,为react 提供redux
import { PropsWithChildren } from 'react'
import { Provider } from 'react-redux'
import { store } from '@/store'
// with Provider
function App(props: PropsWithChildren<any>) {
return (
<Provider store={store}>
<Index>{props.children}</Index>
</Provider>
)
}
export default App