React:TypeScript + react-redux + redux toolkit

2 篇文章 0 订阅
1 篇文章 0 订阅

目录

报错

redux toolkit简易使用笔记


报错

最初我也只是使用redux+react-redux+redux-thunk,但最近使用创建项目,使用dispatch出现了报错

TS2345: Argument of type 'RootThunkAction' is not assignable to parameter of type 'AnyAction'. Property 'type' is missing in type 'RootThunkAction' but required in type 'AnyAction'. 

说没有type属性,reac-redux v7并不会出现该报错,新版v8才会

你可以通过any来避开这个报错(不推荐)

dispatch<any>(delTodo(id))

所以我就浅学了一下redux toolkit

redux toolkit简易使用笔记


store/index.ts

import { configureStore, ThunkAction, Action } from "@reduxjs/toolkit";
import count from "./reducers/count";
const store = configureStore({
  reducer: {
    count,
  },
});
export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  RootState,
  unknown,
  Action<string>
>;
export default store;

使用configureStore创建store

AppDispatch和RootState这两个类型是提供给useSelector, useDispatch用的


store/reducers/count.ts

import { createSlice, PayloadAction } from "@reduxjs/toolkit";

export const countSlice = createSlice({
  name: "count",
  initialState: {
    num: 0,
    status: "foo",
  } as Init,
  reducers: {
    add: (state) => {
      state.num += 1;
    },
    dec: (state) => {
      state.num -= 1;
    },
    custom: (state, action: PayloadAction<number>) => {
      state.num += action.payload;
    },
  },
  extraReducers: (builder) => {},
});

export const { add, dec, custom, changeStatus } = countSlice.actions;

export default countSlice.reducer;

用了createSlice,就可以省去了写actions这一步

countSlice.actions便可以导出定义在reducers里的方法,相当于action了

在组件中使用

import { useSelector, useDispatch } from "react-redux";
import { AppDispatch, RootState } from "../store";
import { add, asyncAdd, asyncDec, custom, dec, odd } from "../store/reducers/count";


export default function Home() {

  const dispatch = useDispatch<AppDispatch>();
  const count = useSelector((state: RootState) => state.count);

  return (
    <div>
      <input type="text" value={value} onChange={change} onKeyUp={keyUp} />
      <div>
        count:{count.num}---{count.status}
      </div>
      <button onClick={() => dispatch(add())}>+1</button>
      <button onClick={() => dispatch(dec())}>-1</button>
      <button onClick={() => dispatch(custom(Number(value)))}>自定义</button>
    </div>
  );
}

PayloadAction<>可以定义payload的类型,如果这次操作需要传参,这在这里定义好参数类型

例如

在调用的时候就能得到类型提示 

 


 如果涉及到异步操作,则要用到createAsyncThunk

export const asyncDec = createAsyncThunk("asyncDec", async () => {
  const res: number = await new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(-100);
      // reject();
    }, 1000);
  });
  return res;
});

在createSlice中的extraReducers处理异步操作

builder.addCase的第一个参数传入createAsyncThunk的返回值.pending(或fulfilled或rejected),

分别是等待、完成、异常三个状态

export const countSlice = createSlice({
  name: "count",
  initialState: {
    num: 0,
    status: "foo",
  } as Init,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(asyncDec.pending, (state, action) => {
        state.status = "loading";
      })
      .addCase(asyncDec.fulfilled, (state, action) => {
        state.num += action.payload;
        state.status = "foo";
      })
      .addCase(asyncDec.rejected, (state, action) => {
        console.log("错误", state, action);
        state.status = "bar";
      });
  },
});
<button onClick={() => dispatch(asyncAdd())}>async+100</button>

redux toolkit官网地址:Redux Toolkit | Redux Toolkit

可以通过下面这行命令,快速下载一个官网提供的demo学习

npx create-react-app my-app --template redux-typescript

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值