前言:针对redux刚开始学习的人员,建议跟随官网慢慢学习
1.先准备一系列的准备工作,项目个根目录写入app文件夹在里面有两个ts文件,hooks和store,它两个的是为了在ts中使用store,在js中是直接可以使用useDispatch和useSelector。
2.store本身就是可以理解为一个仓库,类似于vue的state,在这个里面我们需要注意的是redux的类型,跟着官网弄就行。
import { configureStore } from "@reduxjs/toolkit";
import CounterSlice from "../features/counter/CounterSlice";
const store = configureStore({
reducer: {
counter: CounterSlice,
},
});
// 从 store 本身推断出 `RootState` 和 `AppDispatch` 类型
export type RootState = ReturnType<typeof store.getState>;
// 推断出类型: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch;
export default store;
3.hooks文件是针对js里面的useDispatch和useSelector进行类型推断
import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";
import type { RootState, AppDispatch } from "./store";
// 在整个应用程序中使用,而不是简单的 `useDispatch` 和 `useSelector`
export const useAppDispatch: () => AppDispatch = useDispatch;
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
4.接下来我们就可以使用store了
import { PayloadAction, createSlice } from "@reduxjs/toolkit";
// 为 slice state 定义一个类型
interface CounterState {
count: number;
}
// 使用该类型定义初始 state
const initialState: CounterState = {
count: 0,
};
export const CounterSlice = createSlice({
name: "counter",
initialState,
reducers: {
increment: (state) => {
state.count += 1;
},
decrement: (state) => {
state.count -= 1;
},
// 使用 PayloadAction 类型声明 `action.payload` 的内容
incrementByAmount: (state, action: PayloadAction<number>) => {
state.count += action.payload;
},
},
});
export const { increment, decrement, incrementByAmount } = CounterSlice.actions;
export default CounterSlice.reducer;
5.在组件使用
import "./layout.less";
import { Input, Button } from "antd";
import { useAppSelector, useAppDispatch } from "./app/hooks";
function App() {
const count = useAppSelector((state) => state.counter.count);
const dispatch = useAppDispatch();
return (
<>
<div className="redux">
<Button
onClick={() => {
dispatch({ type: "counter/increment" });
}}
>
增加
</Button>
<Input value={count}></Input>
<Button onClick={() => dispatch({ type: "counter/decrement" })}>
减少
</Button>
<Button >
异步增加
</Button>
</div>
</>
);
}
export default App;
结语:目前值了解到这里,异步方法是thunks里面必备的