reactjs - 用 typescript 定义 react redux 状态
问题描述
我有这样的 todoReducer.ts 文件
import ActionType from "../types";
const initialState = {
items: [],
};
interface Item {
task: string;
priority: string;
id: string;
isActive: boolean;
label: string;
}
function reducer(state = initialState, action: any) {
switch (action.type) {
case ActionType.ADD_ITEM:
return { ...state, items: [action.payload, ...state.items] };
case ActionType.CROSS_ITEM:
return {
...state,
items: state.items.map((e: Item) => {
if (e.id === action.payload) e.isActive = false;
return e;
}),
};
default:
return state;
}
}
export default reducer;
然后像这样的root reducer
import { combineReducers } from "redux";
import authReducer from "./authReducer";
import todoReducer from "./todoReducer";
const reducers = combineReducers({
auth: authReducer,
todo: todoReducer,
});
export default reducers;
export type State = ReturnType<typeof reducers>;
在我的 todoList.jsx 文件中
import {State} from "../store/reducers/index"
const TodoList = ()=>{
const items = useSelector((state:State) => state.todo.items);
...
}
这给了我一个错误
“从不”类型上不存在属性“项目”。
似乎 initialState 的items
对象没有被 ts 识别。
我该如何解决这个问题?
更新 评论后,我添加了
export type State = ReturnType<typeof store.getState>;
解决方案
你应该在什么时候声明类型createStore
const store = createStore(reducers, ...)
export type State = ReturnType<typeof store.getState>;
推荐阅读
- c# - 空响应返回 204
- scala - 避免使用 OptionT 的样板(自然变换?)
- python - 使用 pipenv install -r requirements.txt 找到“.dist-info 目录”
- delphi - ServerSocket 只接收一次
- angular-cli - 将 Angular 6 cli 构建使用 Angular/cli@1.7.4 创建的 Angular 应用程序
- git - 使用 git API 和 cURL 的 Git 分支限制
- ios - Firebase 实时数据库查询因用户身份验证后的安全规则而失败,否则工作
- python - pygame.time.wait() 使程序崩溃
- android - 日期/持续时间的 Droid API 22+ 选项(在 Kotlin 中)?
- python - 无法使用 pandas 和 xlsxwriter 将格式添加到 Excel 工作表