当前位置: 首页 > 知识库问答 >
问题:

前端 - react为何引入store的state会报错呢?

梅安平
2023-05-18

我有如下的使用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报错:

image.png


我这样引入就不会报错:

const { bears, todoList } = useStore((state:any) => state)

共有2个答案

史钊
2023-05-18

因为你的image.png
单词拼错了

周承天
2023-05-18

你用的useState而不是useStore

const todoList = useStore((state: any) => state.todoList);
 类似资料: