React+Redux+Axios项目报404及TS2339错误:DefaultRootState不存在posts属性
问题1:TypeScript报错Property 'posts' does not exist on type 'DefaultRootState'.ts(2339)
错误原因
Redux默认没有内置你自定义的State结构,所以useSelector默认推导的DefaultRootState类型里不存在你注册的posts字段,和你实际的reducer注册逻辑无关。
解决方法
- 先在你的根reducer或者store配置文件中导出全局State类型:
// 你的根reducer文件 import { combineReducers } from "redux"; import posts from './posts' export const rootReducer = combineReducers ({ posts }) // 新增这一行,从根reducer推导全局State类型 export type RootState = ReturnType<typeof rootReducer>
- 两种使用方式二选一:
- 临时指定每次
useSelector的参数类型:// 组件里的useSelector写法 import type { RootState } from '你的根reducer文件路径' const posts = useSelector((state: RootState) => state.posts); - 全局声明默认RootState(推荐,后续不用每次加类型):
新建src/types/react-redux.d.ts类型声明文件,写入以下内容:import 'react-redux'; import type { RootState } from '你的根reducer文件路径'; declare module 'react-redux' { interface DefaultRootState extends RootState {} }
- 临时指定每次
问题2:请求返回Request failed with status code 404错误
错误原因
404是标准的HTTP请求资源不存在错误,说明你Axios发送的请求地址和后端实际提供的接口地址不匹配。
排查解决步骤
- 检查
src/api目录下的Axios配置:确认axios.create设置的baseURL是否正确,端口、接口前缀是否和后端服务一致 - 检查
fetchPosts、createPost两个API方法的请求路径拼写是否正确,比如后端接口是/api/posts就不能写成/post这类拼写错误 - 如果本地开发用了代理转发请求,检查代理配置是否匹配你请求的路径规则,有没有漏写前缀、路径重写规则错误等问题
内容的提问来源于stack exchange,提问作者Nishit Shah
相关产品推荐
相关产品推荐

