react-router-dom with TypeScript

前端 未结 7 577
清歌不尽
清歌不尽 2021-01-30 19:56

I\'m trying to use react router with TypeScript. However, I have certain problems using withRouter function. On the last line, I\'m getting pretty weird error:

A         


        
7条回答
  •  北恋
    北恋 (楼主)
    2021-01-30 20:33

    I use a different approach to fix this. I always separate the different properties (router, regular and dispatch), so I define the following interfaces for my component:

    interface HomeRouterProps {
      title: string;   // This one is coming from the router
    }
    
    interface HomeProps extends RouteComponentProps {
      // Add your regular properties here
    }
    
    interface HomeDispatchProps {
      // Add your dispatcher properties here
    }
    

    You can now either create a new type that combines all properties in a single type, but I always combine the types during the component definition (I don't add the state here, but if you need one just go ahead). The component definition looks like this:

    class Home extends React.Component {
      constructor(props: HomeProps & HomeDispatchProps) {
        super(props);
      }
    
      public render() {
        return ({this.props.match.params.title});
      }
    }
    

    Now we need to wire the component to the state via a container. It looks like this:

    function mapStateToProps(state, ownProps: HomeProps): HomeProps => {
      // Map state to props (add the properties after the spread)
      return { ...ownProps };
    }
    
    function mapDispatchToProps(dispatch): HomeDispatchProps {
      // Map dispatch to props
      return {};
    }
    
    export default connect(mapStateToProps, mapDispatchToProps)(Hello);
    

    This method allows a fully typed connection, so the component and container are fully typed and it is safe to refactor it. The only thing that isn't safe for refactoring is the parameter in the route that is mapped to the HomeRouterProps interface.

提交回复
热议问题