React-Redux项目添加组件遭遇TS2322类型分配错误求助
嘿,我懂你现在卡在哪了——当你手动用ReactDOM.render渲染继承了RouteComponentProps的组件时,TypeScript会因为缺少路由相关的props(比如match)而报错。咱们一步步拆解问题,找到解决方案:
问题根源
你给ListingTitle组件加上了RouteComponentProps继承,这意味着这个组件必须接收路由专属的props(包括match、location、history)。但你直接用<ListingTitle />渲染时,没有传递这些必填的props,TypeScript自然会抛出TS2322类型不匹配的错误。
两种解决思路(按需选择)
思路一:移除RouteComponentProps(推荐,当前场景更适用)
从你的组件代码来看,目前并没有用到任何路由相关的功能(比如获取URL参数、跳转路由),完全没必要让它继承RouteComponentProps。直接把组件改回普通的React组件即可:
import * as React from "react"; import * as ReactDOM from "react-dom"; // 去掉RouteComponentProps继承,组件不需要路由props export default class ListingTitle extends React.Component { public render() { return ( <div> <div className="col desktop-two-thirds tablet-half mobile-full"> <p id="carName" className="car-details-wrapper__car-name"> Fiat </p> <p className="car-details-wrapper__car-spec"> 500 </p> </div> </div> ); } } ReactDOM.render( <ListingTitle />, document.getElementById("react-listing-title") );
思路二:如果需要路由props,手动传递或通过路由渲染
要是你之后打算在ListingTitle里用到路由功能(比如读取URL参数),可以选下面两种方式:
方式A:手动模拟路由props(适合测试/非路由场景渲染)
直接在ReactDOM.render时手动传入路由需要的props,用空对象或模拟值填充:
import * as React from "react"; import * as ReactDOM from "react-dom"; import { RouteComponentProps } from "react-router-dom"; export default class ListingTitle extends React.Component<RouteComponentProps<{}>> { public render() { // 之后可以用this.props.match等路由属性 return ( <div> <div className="col desktop-two-thirds tablet-half mobile-full"> <p id="carName" className="car-details-wrapper__car-name"> Fiat </p> <p className="car-details-wrapper__car-spec"> 500 </p> </div> </div> ); } } // 手动传递路由props,按需填充实际值 ReactDOM.render( <ListingTitle match={{ params: {}, isExact: true, path: "/Details", url: "/Details" }} location={{ pathname: "/Details", search: "", hash: "", state: undefined }} history={{ push: () => {}, replace: () => {}, go: () => {}, goBack: () => {}, goForward: () => {}, createHref: () => "" }} />, document.getElementById("react-listing-title") );
方式B:完全通过react-router路由渲染(最佳实践)
你的路由配置里已经加了<Route path="/Details" component={ListingTitle} />,这说明当用户访问/Details路径时,路由会自动渲染这个组件并传递正确的路由props。这种情况下,你不需要手动调用ReactDOM.render渲染ListingTitle,只需要确保你的根路由组件(比如Layout)正确渲染在MVC视图的根容器里即可。
内容的提问来源于stack exchange,提问作者Jason Evans

