redux在TS中的具体实现思路

       前言:针对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里面必备的

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值