Switch
语句1.创建React项目
npm create react-app my-redux-toolkit
2.安装相关ReduxToolkit包
npm install @reduxjs/toolkit react-redux --save
npm install redux-logger @types/redux-logger --D
1.在src目录上创建一个名为store的文件夹
2.在store文件夹下面创建一个文件名为index.ts作为主入口
3.在store文件夹下面创建一个名为modules的文件夹,用于存放所有的reducer文件
import { configureStore } from "@reduxjs/toolkit";
import logger from "redux-logger";
import { useDispatch, useSelector, TypedUseSelectorHook } from "react-redux";
// 引入每一个reducer
import count from "./modules/testSlice";
export const store = configureStore({reducer: {count},// 配置中间件// RTk已经默认使用了redux-thunk,这里不需要额外引入了// 如果需要一些自定义的中间件,可以通过调用getDefaultMiddleware// 并将结果包含在返回的中间件数组中// 案例中使用了日志的中间件,可以追踪到哪个页面在哪个时候使用了该reducer// 并且可以显示调用前的数据状态和调用后的数据状态middleware: (getDefaultMiddleware) => getDefaultMiddleware({}).concat(logger),
});
// 全局定义 dispatch和state的类型,并导出
// 后面使用过程中直接从该文件中引入,而不需要冲react-redux包中引入
export type RootState = ReturnType;
export type AppDispatch = typeof store.dispatch;
export const useAppDispatch: () => AppDispatch = useDispatch;
export const useAppSelector: TypedUseSelectorHook = useSelector;
import { createSlice } from "@reduxjs/toolkit";
// 定义初始化数据
const initialState = {counter: 0 as number,
};
// 定义一个切片
const counterSlice = createSlice({name: "count",initialState,reducers: {// 定义一个数字递增的actions action.type为 上面的定义的name/和该对象的方法名// 即action.type=count/increment// 在这里一般都是使用同步的reducerincrement: (state, action) => {console.log(state, "state");console.log(action, "action");},},
});
// 导出该action
export const { increment } = counterSlice.actions;
// 默认导出,到处的文件需要在store入口文件引入
export default counterSlice.reducer;
increment: (state, action) => {console.log(state, "state");console.log(action, "action");state.counter += action.payload;},
npm install axios --save
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
1.第一个为字符串,可作为action.type
2.第二个参数接收一个函数,在这里你可以编写一些异步函数,例如发送axios请求.该函数返回三个状态值,分别是pending
, fulfilled
, 和 rejected
(哦豁,这不是Promise,没错,返回的状态值正是一个Promise风格的).
3.定义createAsyncThunk函数
export const channelsAction = createAsyncThunk("home/channels", async () => {
// getUserChannels函数是一个axios的请求
const result = await getUserChannels();
return result.data;
});
4.定义初始化数据
// 定义初始化数据
const initialState = {counter: 0 as number,// 这里懒得写类型了,都不难channels: [] as any,
};
5.接下来在createSlice里面新增一个extraReducers方法,接收一个参数builder,builed是一个对象,调用内部的方法addCase,该方法接收两个参数,第一个是createAsyncThunk的返回值的其中一个,第二个参数是一个函数,这里又接收两个参数
extraReducers: (builder) => {builder.addCase(channelsAction.pending, (state, action) => {// 在这里发送的异步请求还没有返回结果,这时候你还可以摸一下鱼// 例如上个厕所// 在这里也可以添加一些请求的动画// console.log(state);// console.log(action);});builder.addCase(channelsAction.rejected, (state, action) => {// 这里请求出错了,可能是你没洗手// 赶紧跑路吧console.log(state);console.log(action);});builder.addCase(channelsAction.fulfilled, (state, action) => {// 请求成功咯,下班console.log(state);console.log(action);});},
fulfilled
,则将axios的返回值作为dispatch操作的action.payload的值,如果请求失败,状态值改为rejected
,返回的错误信息将作为action.payload的值.import React, { useEffect } from "react";
import { useAppDispatch } from "@/store";
import { channelsAction } from "@/store/modules/testSlice";
const Issue: React.FC = () => {const dispatch = useAppDispatch();useEffect(() => {dispatch(channelsAction());}, [dispatch]);return ;
};
export default Issue;
` 此时,我们已经能在控制台里看到请求到的数据了
builder.addCase(channelsAction.fulfilled, (state, { payload }) => {// 请求成功咯,下班// console.log(state);// console.log(payload);state.channels = payload.channels;});
useAppSelector
import {useAppSelector } from "@/store";
import React, { useEffect } from "react";
import { useAppDispatch, useAppSelector } from "@/store";
import { channelsAction } from "@/store/modules/testSlice";
const Issue: React.FC = () => {const { channels } = useAppSelector((state) => state.count);const dispatch = useAppDispatch();useEffect(() => {dispatch(channelsAction());}, [dispatch]);return ({/* 这里也懒得写ts类型了 */}{channels.map((item: any, index: number) => {return {item.name};})});
};
export default Issue;
为大家准备了一个前端资料包。包含54本,2.57G的前端相关电子书,《前端面试宝典(附答案和解析)》,难点、重点知识视频教程(全套)。
有需要的小伙伴,可以点击下方卡片领取,无偿分享