gpt4 book ai didi

javascript - CreateAsyncThunk 错误 : Actions must be plain objects. 使用自定义中间件进行异步操作

转载 作者:行者123 更新时间:2023-12-03 20:25:11 29 4
gpt4 key购买 nike

我目前正在设置我的 RTK (Redux Toolkit) 并进行了一些小测试。这是我的代码:
存储/index.js

import { configureStore } from '@reduxjs/toolkit'
import { loginSliceReducer } from './views/page/login/loginSlice'

export default configureStore({
reducer: {
login: loginSliceReducer
}
})

loginSlice.js
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import ApiService from '../../services/ApiService'

export const authorize = createAsyncThunk(
'api/authorize',
async (email, password) => {
const response = await ApiService.post(email, password)
return response.data
}
)

export const loginSlice = createSlice({
name: 'login',
initialState: {
loading: true,
token: null,
data: []
},
reducers: {
updateState: (state, action) => {
const { payload } = action
switch (payload.type) {
case AUTH_SUCCESS:
state.loading = false
state.token = payload.token
state.data = payload.data
break
default:
}
}
},
extraReducers: {
[authorize.fulfilled]: (state, action) => {
// ... do state update here
}
}
})

export default loginSlice.reducer
login.js
import React, { useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { authorize } from './loginSlice'

const Login = () => {
const dispatch = useDispatch()
useEffect(() => {
dispatch(authorize('testuser@example.com', 'test123'))
}, [])

return <div>Auth Test</div>
}

上面的代码不起作用。我不断收到此错误: Error: Actions must be plain objects. Use custom middleware for async actions.在这条线上: > 25 | dispatch(authorize('testuser@example.com', 'test123'))请不要介意我在 useEffect 上触发授权,因为这只是检查是否正在调用端点以及检查请求成功后状态是否会更新的测试。 :-D

最佳答案

我遇到了同样的问题,这是由于我添加了额外的中间件造成的。@reduxjs/toolkitconfigureStore有一些默认包含的中间件,但如果你添加任何东西到 middleware属性,它将覆盖这些默认值。
解决方案是包含默认中间件以及您定义的中间件:

import { configureStore, getDefaultMiddleware } from '@reduxjs/toolkit';

import { loginSliceReducer } from './views/page/login/loginSlice';
import { otherMiddleware } from './middlewares/some-other-module';

export default configureStore({
reducer: {
login: loginSliceReducer
},
middleware: [ // Because we define the middleware property here, we need to explictly add the defaults back in.
...getDefaultMiddleware(),
otherMiddleware
]
})
注意,没有必要明确包含 redux-thunk使用 @reduxjs/toolkit 时因为它已经是 getDefaultMiddleware() 的默认中间件的一部分

关于javascript - CreateAsyncThunk 错误 : Actions must be plain objects. 使用自定义中间件进行异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62988990/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com