使用CRA+TypeScript3.5.x时,props.location.state.anime类型报错如何解决?
解决React Router + TypeScript中
location.state.anime类型报错的问题 嘿,我来帮你搞定这个类型报错的问题!你遇到的核心问题是TypeScript默认把props.location.state识别成了{}类型,不知道里面包含anime属性,所以才会弹出那个错误提示。下面是具体的修复步骤:
1. 把自定义State类型绑定到路由Props上
RouteComponentProps支持第二个泛型参数来定义location.state的类型,你已经写了LocationState,但没把它和路由Props关联起来。修改你的ComponentProps接口:
interface ComponentProps extends RouteComponentProps<AnimeId, LocationState> {}
这样TypeScript就明确知道props.location.state的结构是你定义的LocationState,而不是默认的空对象了。
2. 调整类组件的泛型参数顺序
你现在的类组件泛型写混了:React.Component<ComponentProps, IEpisode, LocationState>。React.Component的泛型顺序是Props, 组件内部State, 上下文Context,第三个参数不是路由的state类型,所以直接去掉第三个参数就行:
class AnimeStreaming extends React.Component<ComponentProps, IEpisode> { // ... 你的其他代码 }
3. 优化类型定义(可选但推荐)
虽然你关闭了strictNullChecks,但还是建议给anime指定具体类型,别用any,这样能获得更精准的类型提示:
// 替换成你实际的collection结构 interface AnimeCollection { id: string; title: string; // 其他属性... } type LocationState = { anime: AnimeCollection; };
修改后的关键代码片段
import React from 'react'; import { withRouter, Link, Redirect } from 'react-router-dom' import { RouteComponentProps } from 'react-router'; import { Column, List, Title, PageLoader } from 'rbx'; interface AnimeId { animeId: string; } // 定义具体的Anime类型 interface AnimeCollection { id: string; title: string; // ...你的其他属性 } type LocationState = { anime: AnimeCollection; } interface IEpisode { // ...你的组件状态定义 } // 绑定LocationState到路由Props interface ComponentProps extends RouteComponentProps<AnimeId, LocationState> {} // 修正类组件泛型顺序 class AnimeStreaming extends React.Component<ComponentProps, IEpisode> { constructor(props: ComponentProps) { super(props); this.state = { // ...你的初始状态 } } componentDidMount() { // ...你的逻辑 } render() { const animeEpisodes = this.state.items; let anime = { title: '' } if (!this.props.location.state) { return (<Redirect to='/' />); } else { // 现在TypeScript能识别anime属性了 anime = this.props.location.state.anime; } return ( // ...你的JSX内容 ) } } export default withRouter(AnimeStreaming);
这样修改后,TypeScript就不会再报错,同时还能享受到准确的类型提示。
内容的提问来源于stack exchange,提问作者x1yy
相关产品推荐
相关产品推荐

