【问题标题】:Can't access state using 'useStoreState in react easy-peasy无法使用 'useStoreState 在 react easy-peasy 中访问状态
【发布时间】:2021-06-22 09:57:22
【问题描述】:

我最近决定学习 用 easy-peasy 进行状态管理,并按照基本教程进行操作,但我似乎无法访问状态。 这是应用程序组件:-

import model from './model';   
import Todo from './components/Todo.tsx';  
import { StoreProvider, createStore } from 'easy-peasy';

const store = createStore(model);  
function App() { 
  return (
    <StoreProvider store={store}>
    <div className="App">
      <Todo />
      </div>
    </StoreProvider>
 );
}

export default App;

这里是模型文件'model.js'

export default {
    todos: [
        {
            id: 1
        },
        {
            id: 2
        },
        {
            id: 3
        }
    ]
};

这是 Todo 文件:-

import React from 'react';
import {useStoreState } from 'easy-peasy';

const Todo = () => {
   //The line below does not work for me, when i do 'state.todos' i get an error that todos does not exist on type 
    const todos = useStoreState(state=>state.todos);
    
    return (
        <div>
            
      </div>  
    );
}

export default Todo;

【问题讨论】:

  • 帮助我们进行一些常规调试:useStoreState(state=&gt;console.log(state)) 你得到了什么?错误是打字稿错误还是运行时 JS 错误?
  • 在执行 console.log 时,我确实得到了包含 model.js 文件中定义的“todos”的对象。但我不明白为什么我不能通过“state.todos”访问它。
  • 这又回到了第二个问题——错误是打字稿错误吗,就像在你的编辑器中一样?还是在浏览器中中断?
  • 两者。在编辑器中显示错误,以及在浏览器中显示以下错误。 D:/react/easy_peasy/learner/src/components/Todo.tsx(5,58) 中的 TypeScript 错误:“StateMapper<_pick never>>”类型上不存在属性“todos”。 TS2339
  • 是的,修复了它,你提到的链接似乎很酷,可以更好地理解事情,感谢您的帮助!

标签: reactjs redux react-redux state easy-peasy


【解决方案1】:

尝试删除 .todos 以便

const todos = useStoreState(state=>state.todos);

变成:

const todos = useStoreState(state=>state);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    相关资源
    最近更新 更多