我正在使用 redux,当我向 auth 用户发送 get 请求时,它正在工作,在 cookie 中创建令牌,但在 redux 中状态没有改变,我做错了什么?重新加载页面时,我的令牌和用户数据有效,这里是一些代码示例
成功登录后我的状态是:
{"user":{"isAuthenticated":false}}
但这应该是真的
编辑: 好吧,我在 useEffect 之前登录,它说 true,因为我的令牌是正确的,那么如何在 useEffect 内部或打开页面时将其传递?当它是真的时我想干杯
用户减速器:
import { createReducer } from "@reduxjs/toolkit"
const initialState = {
isAuthenticated: false,
}
export const userReducer = createReducer(initialState, (builder) => {
builder
.addCase('AuthenticateUserRequest', (state) => {
state.loading = true
})
.addCase('AuthenticateUserSuccess', (state, action) => {
state.isAuthenticated = true
state.user = action.payload
state.loading = false
})
.addCase('AuthenticateUserFailure', (state, action) => {
state.isAuthenticated = false
state.error = action.payload
state.loading = false
})
.addCase('ClearErrors', (state) => {
state.error = null
})
})
用户操作:
import axios from "axios"
import { authenticateUserUrl } from '../../constants'
export const authenticateUser = () => async (dispatch) => {
try {
dispatch({
type: 'AuthenticateUserRequest'
})
const { data } = await axios.get(authenticateUserUrl, { withCredentials: true })
dispatch({
type: 'AuthenticateUserSuccess',
payload: data.user,
})
} catch (err) {
dispatch({
type: 'AuthenticateUserFailure',
payload: err.response.data.message
})
}
}
店铺:
import { configureStore } from "@reduxjs/toolkit"
import { userReducer } from "./reducers/user"
const Store = configureStore({
reducer: {
user: userReducer,
},
})
export default Store
应用程序:
import { useContext, useEffect } from "react"
import { authenticateUser } from "./redux/actions/user"
const App = () => {
var store = useContext(ReactReduxContext).store.getState()
useEffect(() => {
Store.dispatch(authenticateUser)
console.log(JSON.stringify(store))
})
事实证明解决方案是:
const { isAuthenticated, user, loading, error } = useSelector((state) => state.user)
useEffect(() => {
Store.dispatch(authenticateUser()) // Dispatch the action once on component mount
}, []) // Empty dependency array to ensure this runs only once
useEffect(() => {
if (isAuthenticated) {
console.log("User State:", { isAuthenticated, user, loading, error })
}
}, [isAuthenticated, user, loading, error])