ReactJS 和 Redux Toolkit:我可以使用"createAsyncThunk()"来执行非异步副作用吗?



这就是我的登录操作的样子,它工作正常:

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">

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

非常感谢!

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

CCD_ 1是对正常的"0"的抽象;暴徒行动;其将";挂起";动作之前和一个";满足"/"被拒绝";之后的操作。如果你不想要这些生命周期操作,你也可以写一个普通的thunk。这些都是如此简单,RTK不包含任何帮助他们。

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

有关更多信息,请参阅官方教程的这一部分

您还有第二个选项。您可以创建一个redux中间件,并且可以在那里执行自定义逻辑。在中间件中,您可以过滤操作,当相应的操作出现时,您可以执行副作用。例如:

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
}

最新更新