react为何引入store的state会报错呢?
我有如下的使用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)
回复
1个回答
test
2024-07-03
你用的useState而不是useStore
const todoList = useStore((state: any) => state.todoList);
回复
适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容