Redux 工具包:创建 Thunk 函数

来源:undefined 2025-01-19 05:08:45 1028

什么是 thunk?

在编程中,thunk 一词指的是执行延迟工作的代码部分,例如 javascript 中的异步函数。

redux 存储本身不处理异步逻辑。它只知道如何:

同步调度动作。 通过减速器更新状态。 通知 ui 有关状态更改的信息。

但是等等,如果是这样的话,我们如何调用 api 并根据它们的响应更新状态,这通常需要时间?我们该如何处理?

这就是 thunk 函数的用武之地。

什么是 thunk 函数?

thunk 函数是为处理异步逻辑(例如调用 api)而创建的函数。它需要两个参数dispatch和getstate来调度动作,并在需要时访问当前状态。

1

2

3

4

5

6

7

8

9

10

11

const getallusers = () => {

return async (dispatch, getstate) => {

dispatch(fetingallusers());

try {

const users = await getusers();

dispatch(userupdated(users));

} catch (err) {

dispatch(logerror(err))

}

}

}

登录后复制

返回的函数是 thunk 函数,getallusers 在本例中被称为 thunk 动作创建者,它将像这样调度:

1

dispatch(getallusers())

登录后复制

如果需要,可以使用 thunk 函数中使用的参数来调度 thunk 动作创建者。

使用 createasyncthunk 创建 thunk

redux toolkit 提供了 createasyncthunk api 来轻松生成 thunk:

1

2

3

4

5

6

7

8

9

import { createasyncthunk } from @reduxjs/toolkit;

export const fetchuserbyid = createasyncthunk(

user/fetchuserbyid,

async (userid) => {

const user = await somehttprequest(userid);

return user;

}

);

登录后复制

fetchuserbyid 是这里创建的 thunk 函数。 createasyncthunk 采用两个参数:

第一个参数是用于生成的操作类型的字符串前缀(例如 user/fetchuserbyid/pending、user/fetchuserbyid/fulfilled 或 user/fetchuserbyid/rejected)。 第二个参数是“有效负载创建者”函数。它应该返回一个包含所需数据或错误的 promise。

为什么使用createasyncthunk?

除了让您为 api 调用创建 thunk 函数之外,createasyncthunk 还会自动调度操作来跟踪 api 请求的状态:

待处理:请求正在进行中。 fulmeded:请求成功。 被拒绝:请求失败。

这真的很有用。例如,当状态处于挂起状态时,我们可以在 ui 中显示加载程序,并让用户知道正在发生某些事情。

在切片中使用 thunk

现在我们已经创建了 fetchuserbyid thunk,我们可以使用 userslice 中的 extrareducers 字段来处理状态状态更改:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

import { createslice } from @reduxjs/toolkit;

const initialstate = {

user: null,

status: idle, // idle | pending | succeeded | failed

error: null,

};

export const userslice = createslice({

name: user,

initialstate,

reducers: {

usernameupdated: (state, action) => {

state.user.username = action.payload;

},

emailupdated: (state, action) => {

state.user.email = action.payload;

},

userdatacleared: (state) => {

state.user = null;

state.status = idle;

},

},

extrareducers: (builder) => {

builder

.addcase(fetchuserbyid.pending, (state) => {

state.status = pending;

})

.addcase(fetchuserbyid.fulfilled, (state, action) => {

state.status = succeeded;

state.user = action.payload;

})

.addcase(fetchuserbyid.rejected, (state, action) => {

state.status = failed;

state.error = action.error.message || something went wrong.;

});

},

});

export const { usernameupdated, emailupdated, userdatacleared } = userslice.actions;

// selector for the status to use in the applications components

export const selectstatus = (state) => state.user.status;

登录后复制

createasyncthunk 条件

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

export const fetchUserById = createAsyncThunk(

"user/fetchUserById",

async (userId) => {

const response = await someHttpRequest(userId);

return response;

},

{

condition(_, { getState }) {

const status = selectStatus(getState());

if (status !== "idle") {

return false;

}

},

}

);

登录后复制

要了解如何将 typescript 与 thunk 函数结合使用,请阅读类型检查 redux thunk。

以上就是Redux 工具包:创建 Thunk 函数的详细内容,更多请关注php中文网其它相关文章!

最新文章