最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is there any way to Route path with question mark? - Stack Overflow

programmeradmin4浏览0评论

I am defining my Route

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

When I enter URL localhost:9000/test?foo=100&bar=100&zoo=100 its is not being redirected to Test ponent. I added console.log(this.props.location.search) in ponentDidMount() but it is giving output as ?foo=100&bar=100&zoo=100

And it is going to my Error page view which is,

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

I have tried to remove the Question mark (?) from URL and added characters like [, ], $ and the URL is hitting Test ponent.

Is there any way If I enter URL = localhost:9000/test?foo=100&bar=100&zoo=100 I get redirected to Test ponent rather than going to an error ponent.

I would appreciate the help.

I am defining my Route

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

When I enter URL localhost:9000/test?foo=100&bar=100&zoo=100 its is not being redirected to Test ponent. I added console.log(this.props.location.search) in ponentDidMount() but it is giving output as ?foo=100&bar=100&zoo=100

And it is going to my Error page view which is,

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

I have tried to remove the Question mark (?) from URL and added characters like [, ], $ and the URL is hitting Test ponent.

Is there any way If I enter URL = localhost:9000/test?foo=100&bar=100&zoo=100 I get redirected to Test ponent rather than going to an error ponent.

I would appreciate the help.

Share Improve this question asked Apr 16, 2019 at 13:52 TEMPTEMP 2352 gold badges7 silver badges17 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

You can pass a path which contains question mark, but you have to parse that inside your ponent instead of the path. You have to install (or create your own) a proper tool to parse the query string. I suggest you to use the query-string one.

After that the route inside the routing file or whereever you use them should look like this:

<Route path="/test" ponent={Test} />

The Test ponent:

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

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

  render() {
    {/* ... */}
  }
}

Inside the above example, the values will contains your query string parameters, for example if the url is that you provided: localhost:9000/test?foo=100&bar=100&zoo=100 the values will be:

{
  foo: 100,
  bar: 100,
  zoo: 100
}
发布评论

评论列表(0)

  1. 暂无评论