reactjs – 如何使用withRouter,connect,React.Component和自定
我有一个使用connect,withRouter并接收自定义属性的React组件.我试图将其转换为TypeScript,我想知道我是否正确地这样做.至少,我现在没有错误.
这是显示概念的代码: import * as React from 'react' import { connect } from 'react-redux'; import { withRouter,RouteComponentProps } from 'react-router'; import { fetchTestLists,newTestList,displayTestList,} from '../../../actions/index'; interface StateProps { testList: any; // todo: use the type of state.myList to have validation on it } interface DispatchProps { fetchTestLists: () => void; newTestList: () => void; displayTestList: (any) => void; // todo: replace any with the actual type } interface Props { // custom properties passed to component className: string; } type PropsType = StateProps & DispatchProps & Props; class MyTest extends React.Component<PropsType & RouteComponentProps<{}>,{}> { constructor(props) { super(props); this.handleCellClick = this.handleCellClick.bind(this); this.newTestList = this.newTestList.bind(this); } componentDidMount() { this.props.fetchTestLists(); } handleCellClick(row,column,event) { this.props.displayTestList(row); } newTestList(e) { this.props.newTestList() } render() { return ( <div className={this.props.className}> </div> ); } } const mapStateToProps = (state): StateProps => ({ testList: state.myList,// todo: define a type for the root state to have validation here }); const dispatchToProps = { fetchTestLists,}; export default withRouter<Props & RouteComponentProps<{}>>(connect<StateProps,DispatchProps>( mapStateToProps,dispatchToProps,)(MyTest) as any); 该组件的使用方式如下:< MyTest className = {“active”} /> 我必须做很多实验才能使这个工作.例如: 1)当我省略withRouter的类型时,如下所示: 2)如果你想知道最后一行是什么,这与https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18999有关,我没有它得到这个错误: TS2345: Argument of type 'ComponentClass<Pick<any,never>> & { WrappedComponent: ComponentType<any>; }' is not assignable to parameter of type 'ComponentType<Props & RouteComponentProps<{}>>'. Type 'ComponentClass<Pick<any,never>> & { WrappedComponent: ComponentType<any>; }' is not assignable to type 'StatelessComponent<Props & RouteComponentProps<{}>>'. Type 'ComponentClass<Pick<any,never>> & { WrappedComponent: ComponentType<any>; }' provides no match for the signature '(props: Props & RouteComponentProps<{}> & { children?: ReactNode; },context?: any): ReactElement<any> | null'. 那么这是正确的方法吗?你在哪里看到问题?我基本上使用所有最新版本,这是我的package.json的一个片段: "react": "^16.2.0","redux": "^3.7.2","react-dom": "^16.2.0","react-redux": "^5.0.6","react-router": "^4.2.0","react-router-dom": "^4.2.2","react-router-redux": "^4.0.8",... "typescript": "^2.7.2","@types/react-redux": "^5.0.15","@types/react-router": "^4.0.22","@types/react-router-dom": "^4.2.4","@types/react": "^16.0.38","@types/react-dom": "^16.0.4", 解决方法
我通过强制安装@ types / react-redux包解决了这个问题.我刚刚从4.4.5更新到5.0.15.
运行新的npm安装可能是值得的–save @ types / react-redux @ 5.0.15. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |