在反应路由器中传递可选参数

Passing optional parameter in react router

假设我有 http://www.example.com/page/#/search 这样的路由:

<Router history={hashHistory}>
  <Route path='/search/' component={SearchPage} />
</Router>

并且当用户使用提供的 nameage 搜索框在页面上进行搜索时(可以省略,也可以同时填写),我希望它重定向至:

http://www.example.com/page/#/search/?name=whatever%20name&age=15

这将显示该特定搜索的结果。这也将允许直接链接到搜索结果。

现在在我的 SearchPage 组件中,如何检查是否提供了 ?name=?age= 或任何其他搜索参数?

在你的容器中说 SearchPage 你可以像这样访问 queryParams

this.props.location.query.yourKey.

举个例子

class SearchPage extends React.Component{
   componentWillMount(){
     const {name, age} = this.props.location.query;
     //here you can give default values if they are empty
     //do whatever you want
   }
}

有两种方法可以实现此目的,您可以使用参数或查询值。

通过参数:

在路由中首先像这样定义你的可选参数:

<Router history={hashHistory}>
   <Route path='/search(/:name)(/:age)' component={SearchPage} />
</Router>

在您的组件中包含 componentWillReceiveProps() 方法,只要组件收到任何新道具,它就会被触发,如下所示:

componentWillReceiveProps(newProps){
   console.log(newProps.params.name, newProps.params.age);
   // here you can check the props value
}

在组件中,您可以通过 this.props.params.name 或年龄来检查值。

通过查询参数:

路由中不需要更改,只需传递 url 中的值并像这样检查:

this.props.location.name or age.

阅读这篇文章以了解 React 中的参数和查询值:https://www.themarketingtechnologist.co/react-router-an-introduction/

随着最新的更新"location.query"没有公开,我们必须使用"location.search"来获取可选的未命名参数。但是,命名的可选参数仍然可以通过 "props.match.params"

读取

路线:

<Route path="/partner/list-space/step-1/:_id?" component={ListSpace}/>

正在获取组件或挂钩中的命名可选参数"id"

let id = props.match.params._id;

从 url.

中获取未命名的可选参数,例如 "space"
http://localhost:3000/partner/list-space/step-1/123?space=new&guests=4

我们必须使用 "querystringify"。

import qs from "querystringify";

const qsParams = qs.parse(props.location.search);

结果:

props.match.params._id => "123" 
qsParams.space => new 
qsParams.guests => 4