存在问题
目标
当reducer和action合并以后就没有模板代码了
createSlice
A function that accepts an initial state, an object of reducer functions, and a "slice name", and automatically generates action creators and action types that correspond to the reducers and state.
createSlice就是将reducer和action捆绑在一起。
action被干掉了,switch没有了。
configureStore
A friendly abstraction over the standard Redux createStore function that adds good defaults to the store setup for a better development experience.
开始使用
npm install @reduxjs/toolkit
底层immer已经帮忙处理
RTK可以兼容目前所有redux结构,下面是redux和RTK混编情况:
首先修改combineReducers
修改前结构
修改后结构
detail引入
useSelector连接产品详情的数据
修改前结构
修改后结构
接下来分发各种action
修改前结构
创建slice的时候会把reducer和action捆绑起来,分发action时候会通过对应action creator指明类型和数据。RTK在绑定reducer和action的时候,会根据reduce人的函数签名,自动生成action creator。所以不需要写重复的action模板代码,现在只需要调用。
修改后结构
createAsyncThunk
A function that accepts a Redux action type string and a callback function that should return a promise. It generates promise lifecycle action types based on the action type prefix that you pass in, and returns a thunk action creator that will run the promise callback and dispatch the lifecycle actions based on the returned promise.
createAsyncThunk accepts three parameters: a string action type value, a payloadCreator callback, and an options object.
createAsyncThunk returns a standard Redux thunk action creator. The thunk action creator function will have plain action creators for the pending, fulfilled, and rejected cases attached as nested fields.
- 首先替换store的创建方式(Redux DevTools插件)
- DetailPage中干掉内容
- 粘贴到slice.ts
- detail中引入getProductDetail
- 处理了异步逻辑,却没有充分利用返回类型。
getProductDetail函数根本就没有返回值,只有dispatch.
现在return的是promise,getProductDetail函数会自动生成
pending、fulfilled、rejected。
- 修改createSlice
修改前
修改后,重命名下fetchStart->[getProductDetail.pending.type]
createAsyncThunk自动映射
pending,fulfilled, andrejected
- useHistory:返回 history 对象,可以使用 useHistory 进行导航;
- useLocation:返回当前URL的 location 对象,每当URL发生变化时,它都会返回一个新的位置;
- useParams:动态参数列表的引用对象,用于获取中的 match.params (动态参数)
- useRouteMatch:主要用于访问匹配数据,而无需实际渲染