我有一个 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
未定义进行调用。
这是怎么回事?这看起来很简单,但我无法让它工作……
从 Zusand文档中,状态可以更新为:
你似乎在代码中结合了这两种方式:
实际情况:
set({...ctx})
。set((state) => undefined)
:。