React+TypeScript中RouteComponentProps矛盾报错求助
解决React-Router RouteComponentProps绑定的矛盾编译错误
我来帮你拆解一下这个看起来矛盾的错误——一边说RouteComponentProps被声明但未使用,一边又说找不到它,其实这是TypeScript类型检测和解析逻辑的小冲突,根源在于你使用交叉类型的方式让TypeScript没正确识别到类型的使用。
问题根源
当你用RouteComponentProps & Props作为组件的Props类型时,由于Props是空接口,TypeScript的静态检测没把交叉类型里的RouteComponentProps认定为“被实际使用”,所以抛出TS6133;同时,类型解析的优先级问题又让它在组件泛型里找不到这个导入的类型,就出现了看似矛盾的TS2304错误。
修正后的代码
下面是调整后的正确代码,我会标注关键修改点:
import * as React from "react"; import { connect } from "react-redux"; import { RouteComponentProps, withRouter } from "react-router-native"; import Example from "../../screens/Example"; // 关键修改1:让Props接口直接扩展RouteComponentProps,替代交叉类型 interface Props extends RouteComponentProps {} interface State {} class ExampleContainer extends React.Component<Props, State> { // 关键修改2:用箭头函数定义方法,自动绑定this,避免回调中this指向错误 isValid = (value: string): void => { if (value !== "") { this.props.history.push('/tasks'); } } render() { return ( <Example callback={(value: string) => this.isValid(value)} /> ); } } const mapDispatchToProps = (_) => ({}); const mapStateToProps = (_) => ({}); // withRouter和connect的包裹顺序没问题,保持原样即可 export default withRouter(connect(mapStateToProps, mapDispatchToProps)(ExampleContainer));
额外的this指向优化
原代码里的isValid是普通函数,当通过子组件的callback调用时,this可能会丢失指向组件实例的上下文,导致this.props报错。除了用箭头函数,你也可以在构造函数里手动绑定:
constructor(props: Props) { super(props); this.isValid = this.isValid.bind(this); } isValid(value: string): void { if (value !== "") { this.props.history.push('/tasks'); } }
这样调整后,两个编译错误都会消失,this.props.history也能正常使用啦。
内容的提问来源于stack exchange,提问作者JoSauderGH
相关产品推荐
相关产品推荐

