【问题标题】:Cannot see the route params in match.params在 match.params 中看不到路由参数
【发布时间】:2019-12-23 16:33:51
【问题描述】:

当我为类别选择家具并为城市选择“San Jose, CA, USA”时,下面的推送会将 URL 重定向到 http://localhost:3000/search?category=furniture&city=San+Jose%2C+CA%2C+USA

    this.props.history.push({
      pathname: '/search',
      search: "?" + new URLSearchParams({category: this.category, city: this.userCity}).toString()
    });

在 App.jsx 中,我定义了如下路由:

<Route path="/search/:category?/:city?" component={props => <EventSearchPage {...props} />}/>

EventSearchPage 组件中,当我尝试访问this.props.match.params 时,我看到类别和城市都是undefined

谁能告诉我哪里出错了?谢谢!

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    发现 queryString 可以像下面这样获取 URL 参数:

    queryString.parse(this.props.location.search)
    

    npm 包链接在这里:https://www.npmjs.com/package/query-string

    【讨论】:

      【解决方案2】:

      当使用 react router 给路由添加参数时,可以这样做,以便将它们提供给组件。

      this.props.history.push({
        pathname: `/search/${this.category}/${this.userCity}`,
      });
      

      路由组件看起来像这样来接收这些参数。

      <Route path="/search/:category?/:city?" component={props => <EventSearchPage {...props} />}/>
      

      react 路由器的文档可以在here找到

      【讨论】:

      • 它不工作。什么时候服用?在 Route 路径之外,它只是找不到页面并返回 404 错误。
      • 哦,我的错,我没有意识到包含? 意味着它将输入路由作为可选参数。这个answer 解释了更多,但我认为如果您有指向http://localhost:3000/search 的链接,您可以保留?
      猜你喜欢
      • 1970-01-01
      • 2021-01-31
      • 2014-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多