无法使用打字稿

时间:2020-09-10 22:34:35

标签: reactjs typescript redux redux-toolkit

我目前正在通过使用React,Redux-toolkit和Typescript创建一个非常简单的待办事项应用程序来学习打字稿。当我尝试使用useSelector从商店访问数据时,我得到一个包含所需值的对象(在本例中为Todo数组)。

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

todos的Console.log:

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

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

如果需要更多信息,请检查完整代码here

干杯,谢谢! (也为可能的错字表示抱歉)

1 个答案:

答案 0 :(得分:0)

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

您可以通过

获取实际的RootState
export const store = configureStore({
    reducer: {
        todos: todosReducer
    }
})

export type RootState = ReturnType<typeof store.getState>;

然后,您实际上会发现待办事项在state.todos.todos中,而不是在state.todos中。