我有如下的使用zustand store的示例:
1、文件:store/index.ts
import { create } from 'zustand'
// 全局状态
export const useStore = create((set) => ({
// 1.bears
bears: 0,
increasePopulation: () => set((state:any) => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 }),
// 2. todoList
todoList: [
{ title: 'demo01', due: '2023-05-05' },
{ title: 'demo02', due: '2023-05-06' },
{ title: 'demo03', due: '2023-05-07' }
]
}))
2、在pages/home页面中:
function Home() {
const bears = useStore((state:any) => state.bears)
const increasePopulation = useStore((state: any) => state.increasePopulation)
const todoList = useState((state:any) => state.todoList) // 这里引入todoList报错
const addBears = () => {
increasePopulation()
}
return (
<>
<h1>zustand状态值: bears = {bears}</h1>
<Button onClick={addBears}> 点击增加🐻 </Button>
<h1>todoList</h1>
<List>
{ todoList.map((item:any, index:number) => {
return <li>{index}. {item.title} --- { item.due } </li>
}) }
</List>
</>
);
};
export default Home;
为何在我的pages/home 页面中会直接报错呢?引入todoList报错:
我这样引入就不会报错:
const { bears, todoList } = useStore((state:any) => state)
你用的useState而不是useStore