为何TSLint抛出TypeScript错误?React+SpaceX API遇TS2741问题
解决TS2741错误:类型'{}'缺少必需属性'mission_name'的问题
嘿,我来帮你搞定这个TypeScript错误!咱们先拆解问题根源,再一步步修复:
核心问题分析
你遇到的TS2741错误,本质是Launches组件的props类型定义错了:
- 你给Launches组件指定的props类型是
ILaunches,这个接口要求必须传入mission_name属性; - 但在App组件里调用
<Launches />时,你完全没传任何props; - 更关键的是:你的Launches组件根本不需要从外部接收
mission_name——它是自己通过componentDidMount从SpaceX API拉取数据的,所以这个props类型完全是多余的。
分步修复方案
1. 修正Launches组件的props类型
把Launches组件的泛型参数里的props类型改成空对象{}(因为它不需要任何外部props):
// Launches组件修正后的开头部分 import * as React from 'react' import LaunchItems from './LaunchItems' interface ILaunches { mission_name: string; } interface IState { pastLaunches: ILaunches[] | null; } // 把React.Component<ILaunches, IState>改成React.Component<{}, IState> class Launches extends React.Component<{}, IState> { state = { pastLaunches: [] } // ... 其他代码不变 }
2. 修复map函数的返回值问题
你当前的launchCards里,map回调函数没有返回值(用了花括号但没写return),导致渲染时什么都显示不出来。同时加上可选链?.避免初始渲染时pastLaunches为null的报错:
// Launches组件的render方法修正 render() { // 用可选链?. + 显式return,或者去掉花括号用隐式返回 const launchCards = this.state.pastLaunches?.map((launch: ILaunches) => { return <LaunchItems title={launch.mission_name} /> }) return ( <div> {launchCards} </div> ) }
3. 优化LaunchItems的props类型(推荐)
现在LaunchItems用了any类型,浪费了TypeScript的类型检查优势,给它定义明确的props接口:
// LaunchItems组件修正 import * as React from 'react'; import { Card } from 'react-bootstrap'; // 定义props接口 interface LaunchItemProps { title: string; } export default function LaunchItem(props: LaunchItemProps) { return ( <Card style={{ width: '18rem' }}> <Card.Body> <Card.Title>{props.title}</Card.Title> <Card.Subtitle className="mb-2 text-muted">Card Subtitle</Card.Subtitle> <Card.Text> Some quick example text to build on the card title and make up the bulk of the card's content. </Card.Text> <Card.Link href="#">Card Link</Card.Link> </Card.Body> </Card> ) }
修正后的完整Launches组件代码
import * as React from 'react' import LaunchItems from './LaunchItems' interface ILaunches { mission_name: string; } interface IState { pastLaunches: ILaunches[] | null; } class Launches extends React.Component<{}, IState> { state = { pastLaunches: [] } componentDidMount() { fetch('https://api.spacexdata.com/v3/launches/past') .then((response) => response.json()) .then((data) => { this.setState({ pastLaunches: data }) console.log('fetch', data) }) } render() { const launchCards = this.state.pastLaunches?.map((launch: ILaunches) => <LaunchItems title={launch.mission_name} /> ) return ( <div> {launchCards} </div> ) } } export default Launches
这样修改后,TS2741错误会消失,同时代码的类型安全性和可读性也会提升~
内容的提问来源于stack exchange,提问作者frootloops
相关产品推荐
相关产品推荐

