ReactJS 和 Redux 工具包:我可以使用 'createAsyncThunk()' 来执行非异步副作用吗?

ReactJS and Redux Toolkit: Can I use 'createAsyncThunk()' to execute non-async side effects?

这是我的登录操作的样子并且它正常工作:

export const login = createAsyncThunk(
'auth/login',
async (data, thunkAPI) => {
    const response = await API.login(data)

    //Store user data in local storage
    Storage.save('user', response.data)

    // Add token to HTTP headers
    API.setToken(response.data.key)

    return response.data
})

现在我需要执行注销功能,但是当使用“createSlice()”时,我没有添加副作用的选项,因为它直接进入减速器(Redux 文档说我们不应该向减速器)

// Slice
const authSlice = createSlice({
    name: 'auth',

    initialState: {
        user: null
    },

    reducers: {
        // Logout
        logout: (state, action) => {
            state.user = null
        },

    },
    extraReducers: {
        [login.fulfilled]: (state, action)=>{
            state.user = action.payload
        },
    }
})

所以我想我可以使用 createAsyncThunk 函数在它到达减速器之前执行副作用:

export const logout = createAsyncThunk(
    'auth/logout',
    async (thunkAPI) => {
        //Remove user data in local storage
        Storage.remove('user')

        // Remove token to HTTP headers
        API.removeToken()
    }
)

“createAsyncThunk”的使用是否合适?

希望有更多经验的人可以帮助解决这个问题。

非常感谢!

这是一种可能的用途,但却是不必要的。

createAsyncThunk 是对正常“thunks 动作”的抽象,它在之前发送“未决”动作,在之后发送“完成”/“拒绝”动作。如果您不想要这些生命周期操作,您也可以只编写一个普通的 thunk。这些非常简单,RTK 不包含任何帮助程序。

const myThunkActionCreator = (id) => (dispatch, getState) => {
  // some sync or async stuff
  dispatch(someResult())
}

dispatch(myThunkActionCreator(5))

有关详细信息,请参阅 this section of the official tutorials

你还有第二个选择。你可以创建一个 redux 中间件,你可以在那里做自定义逻辑。在中间件中,可以对action进行过滤,当相应的action来的时候可以做side-effects。例如:

const customMiddleware = store => next => action => {
  console.log('dispatching', action)
  let result = next(action)
  console.log('next state', store.getState())
  if (action.type === 'EXPECTED_ACTION_TYPE') {
     // do the logic there
  }
  return result
}