Redux Toolkit 提供了许多action匹配工具,常被builder.addMatcher用于筛选符合操作的action
General Purpose(一般匹配工具):
isAllOf
: returns true when all conditions are met 全部匹配,返回true 功能类似 everyisAnyOf
: returns true when at least one of the conditions are met 任一匹配,返回true 功能类似 some
createAsyncThunk
-specific matchers (AsyncThunk专属工具
)
isAsyncThunkAction
- check whether an action was created by createAsyncThunk 检查参数action是否是被 createAsyncThunk创建的例如: isAsyncThunkAction(test1,test2)返回true
isPending
- check whether an action is a 'pending' action creator from thecreateAsyncThunk
promise lifecycle. 判断当前action是否处于pending状态isFulfilled
- 判断当前action是否处于fulfilled状态isRejected
- 判断当前action是否处于rejected状态isRejectedWithValue
- 判断当前action是否处于由rejectWithValue函数结束
使用方法:
import { createAsyncThunk, isAllOf, isAnyOf } from '@reduxjs/toolkit';
export const test1 = createAsyncThunk(
'cunter/test1',
async (id,{ requestId })=>{
return {id,requestId,flag:false};
}
);
export const test2 = createAsyncThunk(
'cunter/test2',
async (id,{ requestId })=>{
return {id,requestId,flag:true};
}
);
//自定义判断
function hasFlag(action){
return action.payload.flag
}
.....
extraReducers: (builder)=>{
builder
.addMatcher(isAllOf(test2.fulfilled,hasFlag),(state,action)=>{
console.log('isAllOf:',action.payload);
})
.addMatcher(isAnyOf(test1.fulfilled,test2.fulfilled),(state,action)=>{
console.log('isAnyOf: ',action.payload);
})
},
.....