首页 > 解决方案 > 提供查询参数时显示 404 的反应查询字符串

问题描述

我是 React 的新手,并试图根据 http://localhost:3000/show?name=james之类的名称查询来呈现页面

所以我最初将路线添加为:

<BrowserRouter>
<Switch>    
<Route path='*' component={ErrorComponent} />} />
<Route path="show(/:name)" name="name" component={Show}></Route>
</Switch>
</BrowserRouter>

然后我尝试渲染组件 Show 如下所示:

import React, { Component } from 'react';
import queryString from 'query-string';
class Show extends Component {
  componentDidMount(){
    console.log(this.props.location.search);
    const values = queryString.parse(this.props.location.search);
    console.log(values.name);
  }


  render() {
    const { params } = this.props.match;
    return <div>
      <h4>About</h4>
      <p>This is About page.</p>
      {params.id ? <b>ID: {params.id}</b> : <i>ID is optional.</i>}
    </div>
  }
}

export default Show;

然后当我尝试显示页面时

http://localhost:3000/show?name=james

它总是显示 404。不确定我做错了哪一部分。任何帮助表示赞赏。我也在使用 react-router-dom 5.1.2 。谢谢。

标签: javascriptreactjsreact-router-dom

解决方案


编辑:不敢相信我最初没有注意到这一点......

您需要将您的path="*"路线放在底部,Switch否则它将匹配所有内容,并且它下面的任何内容甚至都没有机会匹配,因为Switches 仅匹配一条路线。当然,确保您的路由路径设置正确(如下)的描述也适用。

      <Switch>
        <Route path="/show/:name?" component={ShowRouteParam} />
        <Route path="*">ERROR 404</Route>
      </Switch>

https://codesandbox.io/s/elated-browser-d0sew?file=/src/App.js


路由与查询参数不匹配。

“请注意:由 path-to-regexp 返回的 RegExp 旨在与路径名或主机名一起使用。它无法处理 URL 的查询字符串或片段。”

根据您的操作方式,您可以将 id 作为路由的可选部分,也可以将其作为普通查询参数

选项1:

<Route path="/show/:name?" component={Show}></Route>

零件:

import React, { Component } from 'react';
import queryString from 'query-string';
class Show extends Component {
  componentDidMount(){
    console.log(this.props.location.search);
    const values = queryString.parse(this.props.location.search);
    console.log(values.name);
  }


  render() {
    const { params } = this.props.match;
    return <div>
      <h4>About</h4>
      <p>This is About page.</p>
      {params.name ? <b>ID: {params.name}</b> : <i>Name is optional.</i>}
    </div>
  }
}

export default Show;

选项 2:

<Route path="/show" component={Show}></Route>

零件:

import React, { Component } from 'react';
import queryString from 'query-string';
class Show extends Component {
  componentDidMount(){
    console.log(this.props.location.search);
    const values = queryString.parse(this.props.location.search);
    console.log(values.name);
  }


  render() {
    const values = queryString.parse(this.props.location.search);
    return <div>
      <h4>About</h4>
      <p>This is About page.</p>
      {values.name ? <b>ID: {values.name}</b> : <i>Name is optional.</i>}
    </div>
  }
}

export default Show;

工作示例:https ://codesandbox.io/s/silent-rain-n61zs


推荐阅读