reactjs 当extraReducer完成工作时,是否会触发ListenerMiddleware?

c6ubokkw  于 12个月前  发布在  React
关注(0)|答案(1)|浏览(173)

我在store.ts中定义了一个Redux createListenerMiddleware

export const listenerMiddleware = createListenerMiddleware()

listenerMiddleware.startListening({
    actionCreator: myAction,
    effect: (action, listenerApi) => {
      //  do job
    }
})

字符串
然后myAction action在seprate MyAction-slice.ts中定义如下:

const applicationSlice = createSlice({
    name: 'app',
    initialState: initialState,
    reducers: {
        myAction(state) {
            // do pure functional code here
        },
    }
})


当我从一个React组件调用myAction时,它工作得很好(首先myAction完成了它的工作,然后createListenerMiddleware已经被触发了,例如:

return (
    <>
        <button onClick={() => dispatch(myAction())}>
    </>
)


然而,我也有一个createAsyncThunkMyAction-slice.ts中定义如下:

export const myAsyncAction = createAsyncThunk(
    'app/async',
    async () => {
        const promiseData = await axios.get(`https://localhost:8888/hello`)
        // handle errors for promiseData
        return promiseData
    }
)


然后我声明createSlice中的thunk如下:

...
extraReducers: (builder) => {
     builder
        .addCase(myAsyncAction.fulfilled, (state, payload) => {
            // change state with a pure functional way
        })
...


MyAction-slice.ts文件的末尾,我将操作导出为:

export const {myAction} = applicationSlice.actions


我的问题是,我希望以某种方式“挂钩”到myAsyncAction.fulfilled减速器使用createListenerMiddleware,同样的方式,我为myAction减速器。这是可能的吗?

mcvgt66p

mcvgt66p1#

你的myAsyncAction.fulfilled也是一个ActionCreator
将其添加到createAsyncThunk之后的MyAction-slice.ts中:

export const myAsyncActionCreator = myAsyncAction.fulfilled as AsyncThunkFulfilledActionCreator<AxiosResponse<any, any>, AsyncThunkConfig>

字符串
extraReducers中将myAsyncAction.fulfilled替换为myAsyncActionCreator
然后你的createListenerMiddleware看起来像(store.ts):

export const listenerMiddleware = createListenerMiddleware()

listenerMiddleware.startListening({
    actionCreator: myAsyncActionCreator,
    effect: (action, listenerApi) => {
      //  do job
    }
})


另外,不要忘记将prepend这个监听器放到你的configureStore中,就在你的reducers列表之后:

export const store = configureStore({
reducer: {...}
middleware: (getDefaultMiddleware) =>
  getDefaultMiddleware().prepend(listenerMiddleware.middleware),
})


按照同样的想法,你也可以创建myAsyncAction.rejected动作创建器,并以相同的方式导出它,并使用:

listenerMiddleware.startListening({
  actionCreator: myAsyncActionCreatorRejected

相关问题