【问题标题】:React Routing with Dynamic Route Unable to find this.props.match.params使用动态路由反应路由无法找到 this.props.match.params
【发布时间】:2019-06-07 02:48:09
【问题描述】:

我有一个 React BrowserRouter,其中有三个路由,如下所示:

<BrowserRouter>
            <Switch>
                <Route exact
                       path="/"
                       component={(routeProps: object) => (
                           <Component1 toggle="Previous" {...routeProps} />
                       )}
                />
                <Route path="/active"
                       component={(routeProps: object) => (
                           <Component1 toggle="Active" {...routeProps} />
                       )}
                />
                <Route path="/items/:id"
                       render={(props) => <Component2 {...props}/>}
                />
            </Switch>
</BrowserRouter>

我正在尝试将 id 传递到 Component2 中,如图所示,以便通过 get api 调用按 id 获取项目。我的 Component2 如下所示:

export default class Component2 extends React.Component<Props & RouteComponentProps, State> {

    public constructor(props: Props & RouteComponentProps) {
        super(props);
        this.state = {
            item: {
                //Item initialization
            }
        };
    }

    public async componentWillMount() {
        let job = await ItemService.fetch(this.props.match.params);
        this.setState({item: item});
    };


    public render() {
        let {item} = this.state;
        return (
            <div className="item-details">
                <Component3 item={item}/>
            </div>

        )
    }
}

但是,我在包含 this.props.match.params.id 的行上收到错误消息。

  • 第一个错误是如果我不包括 RouteComponentProps,this.props.match.params 状态:Property match does not exist on type &lt;Readonly&lt;Props&gt; &amp; Readonly&lt;ReactNode&gt;
    • 还有另一个 Stack Overflow 帖子导致您需要在 ReactComponent 中使用 RouteComponentProps 才能找到道具,但没有解释原因。
  • 如果我添加 RouteComponentProps,我会修复第一个错误,但仍然无法从参数中获取 id。我收到错误:property id does not exist on type {}

在搜索了关于 SO 的问题和许多反应路由示例之后,我被卡住了。我的最终目标是拥有一个组件(Component2),它将:

  1. 当 url 匹配 items/:id(即/items/3)时被路由到
  2. 将 3 的 id 传递给该组件并调用后端获取项目
  3. 将项目从后端调用保存到状态(组件2的本地状态)
  4. 将该项目从状态传递到子组件

我也很好奇两者之间的区别:

  • React.Component
  • React.Component&lt;Props&gt;
  • React.Component&lt;Props, State&gt;
  • React.Component&lt;Props &amp; RouteComponentProps, State&gt;

当我使用上面的 React.Components 切换 Component 声明时,我对 &lt;Route 中的组件的引用会产生错误。

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    RouteComponentProps 有一个可选的泛型参数(默认为{})来指定预期的参数是什么。类型声明是:

    export interface RouteComponentProps<Params extends { [K in keyof Params]?: string } = {}, C extends StaticContext = StaticContext, S = H.LocationState> {
      history: H.History;
      location: H.Location<S>;
      match: match<Params>;
      staticContext?: C;
    }
    
    export interface match<Params extends { [K in keyof Params]?: string } = {}> {
      params: Params;
      isExact: boolean;
      path: string;
      url: string;
    }
    

    因此,如果您将用法声明为 RouteComponentProps&lt;{ id: string}&gt;,则它应该正确输入。

    编辑:

    我也很好奇:

    对于这些选项中的大多数,只是如果您不指定泛型类型,则假定类型为{}。所以React.Component 等价于React.Component&lt;{}, {}&gt; 并且 props 和 state 都将被输入为一个空对象。

    当您有&lt;Props &amp; RouteComponentProps&gt; 时,这是an intersection type,这意味着组件道具将同时PropsRouteComponentProps 合并在一起。

    【讨论】:

    • 为什么我首先需要一个 RouteComponentProps?多个教程(即herehere)甚至都不使用它。如果我想要 id 作为数字而不是字符串怎么办?
    • 所有路由参数都是字符串(因为它们在 url 中) - 如果它们应该是数字,您必须检查并解析/转换它们。
    • React Router passes the props defined in RouteComponentProps to your components 这样你就可以获得路由参数之类的东西。
    猜你喜欢
    • 2021-02-05
    • 2023-03-30
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 2016-06-05
    相关资源
    最近更新 更多