【问题标题】:React-router with TypeScript, match parameters are always undefined带有 TypeScript 的 React-router,匹配参数始终未定义
【发布时间】:2019-12-14 14:51:44
【问题描述】:

我想做这种路由:localhost:3000/function/page 其中function 告诉应用程序哪个函数应该处理这个url,page 告诉我们在特定函数中的哪个部分。

const App: React.FC = () => {
  return (
    <Router>
      <div className="App">
        <Route component={SignUp} path="/signup/:page" />
      </div>
    </Router>
  );
}

interface MatchProps extends RouteComponentProps<any> {
  page: string;
}

class SignUp extends React.Component<MatchProps> {
  public render(){
    console.log(this.props.page)
  }
}

然后我通过localhost:3000/signup/1访问这个页面,在控制台我只能得到undefined的结果。

【问题讨论】:

    标签: reactjs typescript routing react-router


    【解决方案1】:

    这是解决方案:

    import { match } from "react-router-dom";
    
    interface DetailParams {
      id: string;
    }
    
    interface DetailsProps {
      required: string;
      match?: match<DetailParams>;
    }
    
    
    class Signup extends React.Component<DetailsProps, any> {
      render(){
        const match = this.props.match;
        console.log(match.params.page)
      }
    }
    

    【讨论】:

      【解决方案2】:

      使用this.props.match.params.page 代替this.props.page 可以解决问题。

      但它仍然不完美。 this.props.match.params.page 的类型为 any。我该如何限制它。

      【讨论】:

      • 我建议您通过编辑帖子或创建新问题来提出后续问题。
      • @ggorlen 当然。谢谢。我先搜索现有的答案。
      猜你喜欢
      • 2020-09-03
      • 1970-01-01
      • 2018-09-18
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 2019-06-30
      相关资源
      最近更新 更多