Zusstand useStore - arg 在重新渲染时未定义

问题描述 投票:0回答:1

我的 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
未定义。

这里有什么?这看起来很简单,但我无法让它工作......

reactjs zustand
1个回答
0
投票

从 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}))

实际发生了什么:

  1. 状态设置正确:
    set({...ctx})
  2. 状态再次设置为 set() 函数返回的值(void,即未定义):
    set((state) => undefined)
© www.soinside.com 2019 - 2024. All rights reserved.