有没有办法用问号路由路径?
Is there any way to Route path with question mark?
我正在定义我的路线
<Route path={['/test', '/test\?foo=:id&bar=:id\&zoo=:id']} component={Test} />
当我输入 URL localhost:9000/test?foo=100&bar=100&zoo=100
时,它没有被重定向到测试组件。我在 componentDidMount() 中添加了 console.log(this.props.location.search)
但它给出的输出为 ?foo=100&bar=100&zoo=100
它会转到我的错误页面视图,
<Route path="" component={ErrorPage} />
我已尝试从 URL 中删除问号 (?) 并添加 [ ], $ 等字符,并且 URL 正在命中测试组件。
有什么办法如果我输入 URL = localhost:9000/test?foo=100&bar=100&zoo=100
我会被重定向到测试组件而不是错误组件。
非常感谢您的帮助。
您可以传递一个包含问号的 path
,但您必须在组件内部而不是路径中解析它。您必须安装(或创建自己的)合适的工具来解析查询字符串。我建议你使用 query-string
一个。
之后,路由文件中的路由或您使用它们的任何地方应该如下所示:
<Route path="/test" component={Test} />
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() {
{/* ... */}
}
}
在上面的示例中,值将包含您的查询字符串参数,例如,如果 url 是您提供的:localhost:9000/test?foo=100&bar=100&zoo=100
,则值将是:
{
foo: 100,
bar: 100,
zoo: 100
}
我正在定义我的路线
<Route path={['/test', '/test\?foo=:id&bar=:id\&zoo=:id']} component={Test} />
当我输入 URL localhost:9000/test?foo=100&bar=100&zoo=100
时,它没有被重定向到测试组件。我在 componentDidMount() 中添加了 console.log(this.props.location.search)
但它给出的输出为 ?foo=100&bar=100&zoo=100
它会转到我的错误页面视图,
<Route path="" component={ErrorPage} />
我已尝试从 URL 中删除问号 (?) 并添加 [ ], $ 等字符,并且 URL 正在命中测试组件。
有什么办法如果我输入 URL = localhost:9000/test?foo=100&bar=100&zoo=100
我会被重定向到测试组件而不是错误组件。
非常感谢您的帮助。
您可以传递一个包含问号的 path
,但您必须在组件内部而不是路径中解析它。您必须安装(或创建自己的)合适的工具来解析查询字符串。我建议你使用 query-string
一个。
之后,路由文件中的路由或您使用它们的任何地方应该如下所示:
<Route path="/test" component={Test} />
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() {
{/* ... */}
}
}
在上面的示例中,值将包含您的查询字符串参数,例如,如果 url 是您提供的:localhost:9000/test?foo=100&bar=100&zoo=100
,则值将是:
{
foo: 100,
bar: 100,
zoo: 100
}