首页 > 其他分享 >Redux 教程3 应用的结构

Redux 教程3 应用的结构

时间:2023-02-07 16:01:34浏览次数:35  
标签:异步 教程 const dispatch thunk export 应用 action Redux

应用的结构

这一篇实际上和快速上手的内容差不多,程序范例里其实就是多了一个 thunk ,另外介绍了redux devTools 应该怎么使用。

在计算机编程中,thunk是一个用于向另一个子程序注入计算的子程序。Thunks主要用于延迟计算,直到需要其结果,或在其他子程序的开始或结束时插入操作。它们在编译器代码生成和模块化编程中还有许多其他应用。

我理解,redux的thunk 也是一个actionCreator,但是他不直接返回action,而是返回一个(能创造一个action对象的)函数。
正常同步操作,dispatch的参数就是一个action对吧。
但是,一个异步的操作,传不了state,比如你需要跟服务器查你还剩多少余额,肯定得等服务器返回数据,把这个数据装进payload,组装成action,然后再dispatch。

thunk 返回的函数,就是干上面的事儿,做一个异步操作,等有结果了封装action,并dispatch。

Redux Thunk is a middleware that lets you call action creators that return a function instead of an action object. That function receives the store’s dispatch method, which is then used to dispatch regular synchronous actions inside the function’s body once the asynchronous operations have been completed.

注意一点啊,thunk 他的构造形式有点绕,他一般接受一个数据(比如UI给的什么什么东西),然后返回一个函数,就叫t吧,
t的签名一定包含了一个dispatch 如下:
(dispatch)=>{
//异步操作
//根据异步操作的结果封装 action
//dispatch (action)
}

但我现在有个疑问,这个thunk里边的 dispatch从哪来的?
另外你要是用Typescript,thunk这块儿还得改改,因为默认的 dispatch参数是个AnyAction,thunk 返回一个函数他不是action。
具体怎么改,很简单,定义一个AppThunk 类型(注意,这个名字随便起的,核心在于,告诉Typescript,这是个thunk类型的东东),rtk给了一个ThunkAction类型,具体如下,这是文档上的sample里的内容吖。


// store.ts
import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit';
import counterReducer from '../features/counter/counterSlice';

export const store = configureStore({
  reducer: {
    counter: counterReducer,
  },
});

export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  RootState,
  unknown,
  Action<string>
>;


//counterSlice.ts
//这是手写的thunk
export const incrementIfOdd =
  (amount: number): AppThunk =>
  (dispatch, getState) => {
    const currentValue = selectCount(getState());
    if (currentValue % 2 === 1) {
      dispatch(incrementByAmount(amount));
    }
  };

当然了,你要是嫌麻烦,就不用手写thunk,rtk给了 createAsyncThunk 这个工具,

export const incrementAsync = createAsyncThunk(
  'counter/fetchCount',
  async (amount: number) => {
    const response = await fetchCount(amount);
    // The value we return becomes the `fulfilled` action payload
    return response.data;
  }
);

这个incrementAsync 就是个thunk,可以直接抛给dispatch完成异步操作。
不信你看他的类型

具体Typescript类型体操是怎么做的,我弄不明白,反正不影响使用,就酱吧。。

但是我现在还有个问题,就是,thunk 中的dispatch 是怎么注入的?
我看了一会源码,觉得脑子不是我的了,所以现在还是当做,“我就是知道”dispatch 能给thunk注入一个dispatch 。 就酱。

上面的东西有点絮叨,下面开始还原文档吖。

标签:异步,教程,const,dispatch,thunk,export,应用,action,Redux
From: https://www.cnblogs.com/nulixuexipython/p/17098231.html

相关文章