[React Router v4] Parse Query Parameters

React Router v4 ignores query parameters entirely. That means that it is up to you to parse them so that you can use that additional information as required. There are several strategies for doing this that we will look at.

 

There are tow ways to pass query params in path:

      <NavLink to="/query?id=123">Demo123</NavLink>
      <NavLink to={{pathname: '/query', search: 'id=456'}}>Demo456</NavLink>

First is append ?id=123 to the end of path.

Second is using 'search' prop.

 

React Router no longer help to parse query parameters for us, we can use new web api 'URLSearchParams':

                <Route path="/query" render={({match, location}) => {
                    return (
                        <div>
                            <pre>
                               {JSON.stringify(match, null, 2)}
                            </pre>
                            <pre>
                                {JSON.stringify(location, null, 2)}
                            </pre>
                            <h1>Search id: {new URLSearchParams(location.search).get('id')}</h1>
                            <h2>new URLSearchParams(location.search).get('id')</h2>
                        </div>
                    )
                }}></Route>

posted @ 2017-03-21 19:19  Zhentiw  阅读(342)  评论(0编辑  收藏  举报