语法
2024年02月26日
一、create
定义状态
import {create} from 'zustand';
interface UseNumStateType {
num: number;
setNum: (value: number) => void;
}
const useNum = create<UseNumStateType>()((set: any) => ({
num: 0,
setNum: (value) => set(() => ({num: value})),
}));
export {useNum};
使用状态
import React from 'react';
import {useNum} from './context/zustand';
function App() {
const [num, setNum] = useNum((state: UseNumStateType) => [state.num, state.setNum]);
return (
<div className="app">
{num}
<button onClick={() => setNum(num + 1)}>加一</button>
</div>
);
}
export default App;