有没有办法用问号路由路径?

TEM*_*EMP 2 javascript react-router-dom

我正在定义我的路线

<Route path={['/test', '/test\\?foo=:id&bar=:id\\&zoo=:id']} component={Test} />

当我输入 URL 时,localhost:9000/test?foo=100&bar=100&zoo=100它没有被重定向到测试组件。我添加console.log(this.props.location.search)了 componentDidMount() 但它给出的输出为?foo=100&bar=100&zoo=100

它将转到我的错误页面视图,即,

<Route path="" component={ErrorPage} />

我试图从 URL 中删除问号 (?) 并添加了 [、]、$ 等字符,并且 URL 正在点击测试组件。

有什么办法如果我输入 URL =localhost:9000/test?foo=100&bar=100&zoo=100我被重定向到测试组件而不是去错误组件。

我将不胜感激。

kni*_*ton 6

您可以传递path包含问号的 a ,但您必须在组件内部而不是路径中解析它。您必须安装(或创建自己的)合适的工具来解析查询字符串。我建议你使用那个query-string

之后,路由文件内的路由或您使用它们的任何地方都应如下所示:

<Route path="/test" component={Test} />
Run Code Online (Sandbox Code Playgroud)

Test组件:

import React from 'react';
import queryString from 'query-string';

class Test extends React.Component {
  componentDidMount() {
    const { location: { search } } = this.props;
    const values = queryString.parse(search);
    // Use the values to whatever you want.
  }

  render() {
    {/* ... */}
  }
}
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,值将包含您的查询字符串参数,例如,如果 url 是您提供的:localhost:9000/test?foo=100&bar=100&zoo=100值将是:

{
  foo: 100,
  bar: 100,
  zoo: 100
}
Run Code Online (Sandbox Code Playgroud)