Zustand是一个用于管理状态的JavaScript库。它提供了一种简洁而强大的方式来管理应用程序的状态,特别适用于React应用程序。
这里我不谈源码(因为我也是菜鸡一个),只谈用法
话不多说 直接上通俗易懂的demo!!
src/store.ts:
import create, { SetState } from 'zustand';
interface AuthState {
isAuthenticated: boolean;
user: {
username: string;
password: string;
} | null;
login: (username: string, password: string) => void;
logout: () => void;
}
const useAuthStore = create<AuthState>((set: SetState<AuthState>) => ({
isAuthenticated: false,
user: null,
login: (username: string, password: string) =>
set((state: AuthState) => ({ isAuthenticated: true, user: { username, password } })),
logout: () => set((state: AuthState) => ({ isAuthenticated: false, user: null })),
}));
export default useAuthStore;
src/components/LoginForm.tsx: (登录)
import React, { useState } from 'react';
import useAuthStore from '../store';
function LoginForm(): JSX.Element {
// 从 useAuthStore 中获取 isAuthenticated 状态
const isAuthenticated = useAuthStore((state) => state.isAuthenticated);
// 从 useAuthStore 中获取 login 方法
const login = useAuthStore((state) => state.login);
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const handleLogin = (e: React.FormEvent) => {
e.preventDefault();
if (username.trim() !== '' && password.trim() !== '') {
// 调用 login 方法 传入username,password
login(username, password);
setUsername('');
setPassword('');
}
};
if (isAuthenticated) {
return <p>You are logged in.</p>;
}
return (
<form onSubmit={handleLogin}>
<input
type="text"
placeholder="Username"
value={username}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setUsername(e.target.value)
}
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setPassword(e.target.value)
}
/>
<button type="submit">Login</button>
</form>
);
}
export default LoginForm;
src/components/LogoutButton.tsx: (退出)
import React from 'react';
import useAuthStore from '../store';
function LogoutButton(): JSX.Element | null {
const isAuthenticated = useAuthStore((state) => state.isAuthenticated);
const logout = useAuthStore((state) => state.logout);
if (!isAuthenticated) {
return null;
}
return <button onClick={logout}>Logout</button>;
}
export default LogoutButton;
看起来代码很长 其实很多都是业务代码 其实Zustand用起来非常简单 !!!