【问题标题】:Can't access data from redux toolkit with typescript无法使用 typescript 从 redux 工具包访问数据
【发布时间】:2020-09-10 22:34:35
【问题描述】:

我目前正在通过使用 React、Redux-toolkit 和 Typescript 创建一个非常简单的 todo 应用程序来学习 typescript。当我尝试使用 useSelector 从存储中访问数据时,我得到一个包含我想要的值的对象(在本例中为 Todo 数组)。

//TodoList.tsx
const todos = useSelector(selectTodos)

待办事项的控制台.log:

Object { todos: (1) […] }
//TodoSlice.tsx
export const selectTodos = (state: RootState): Todo[] => state.todos

问题是我无法访问数组,因为根据 TS 编译器,这个值不存在(但根据控制台它在那里!)

如果您想了解更多信息,请查看完整代码here

干杯,提前感谢! (也很抱歉可能的错别字)

【问题讨论】:

    标签: reactjs typescript redux redux-toolkit


    【解决方案1】:

    实际上,您定义为 RootState 的内容不是根状态,而只是您的切片状态类型。

    您可以通过以下方式获取您的实际RootState

    export const store = configureStore({
        reducer: {
            todos: todosReducer
        }
    })
    
    export type RootState = ReturnType<typeof store.getState>;
    

    然后你会注意到你的待办事项在state.todos.todos,而不是state.todos

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-14
      • 1970-01-01
      • 2021-08-24
      • 2018-11-17
      • 1970-01-01
      • 2022-12-31
      • 2021-01-05
      相关资源
      最近更新 更多