我的 Zustand 商店在我登录应用程序并更新商店后行为异常。
这是我的商店:
import {create} from 'zustand'
import {ITRUserInfoDTO, LoginResponse} from "../itr-client";
export type UserContextValue = {
credentials: LoginResponse | null,
expiration: number | null,
user: ITRUserInfoDTO | null
}
export interface AuthState extends UserContextValue {
loggedIn: (ctx: UserContextValue) => void
logout: () => void
}
export const LOGGED_OUT_USER_CONTEXT: UserContextValue = {
credentials: null,
expiration: null,
user: null
}
export const useAuthStore = create<AuthState>(
(set) => ({
...LOGGED_OUT_USER_CONTEXT,
loggedIn: (ctx: UserContextValue) => set((state) => set({...ctx})),
logout: () => set((state) => set({...LOGGED_OUT_USER_CONTEXT,}))
}));
这是我的组件:
export default function LoginPage() {
const {user, loggedIn} = useAuthStore(useShallow(a => ({user: a.user, loggedIn: a.loggedIn})))
const [searchParams, setSearchParams] = useSearchParams();
const redirectLocation = searchParams.get('redirect');
const navigate = useNavigate()
const go = () => redirectLocation > 0 ? navigate(redirectLocation, {replace: true}) : navigate('/home', {replace: true});
// useEffect(() => {
// if (user) {
// go()
// }
// })
const tryLogin = useCallback((loginDTO) => {
const authApi = new AuthenticationApi();
authApi.authenticate({loginDTO})
.then(loginResult => {
const configuration = new Configuration({accessToken: loginResult.token});
const userInformationApi = new UserInformationApi(configuration);
userInformationApi.getMe().then(me => {
const cu = {
credentials: loginResult,
expiration: new Date().getTime() + loginResult.expiresIn,
user: me,
}
// alert(JSON.stringify(cu))
loggedIn(cu)
}).catch(e => {alert(`Error: ${JSON.stringify(e)}`); console.error(e)});
})
.catch(error => console.error('Error', error))
.finally(() => console.log("Done logging in"))
}, [loggedIn, user])
我登录正常,在调用
loggedIn(cu)
后的回调中,我收到错误。
我认为页面重新渲染并抛出错误,即:
Uncaught TypeError: a is undefined
这显然是指在重新渲染时调用
useAuthStore(useShallow(a => (
且 a
未定义。
这里有什么?这看起来很简单,但我无法让它工作......
从 Zustand 文档,状态可以更新为:
import { create } from 'zustand'
const useStore = create((set) => ({
bears: 0,
// based on previous state
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
// without using the previous state
removeAllBears: () => set({ bears: 0 }),
updateBears: (newBears) => set({ bears: newBears }),
}))
您似乎在代码中结合了两种方式:
// This line is the issue
loggedIn: (ctx: UserContextValue) => set((state) => set({...ctx})),
// Fix:
loggedIn: (ctx: UserContextValue) => set({...ctx}),
logout: () => set({...LOGGED_OUT_USER_CONTEXT}))
实际发生了什么:
set({...ctx})
。set((state) => undefined)
。