1

说我有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=或任何其他搜索参数?

回答

1

在容器中说SearchPage你可以这样

this.props.location.query.yourKey访问queryParams

举个例子

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 
    } 
} 
0

有实现这个要么你可以使用params中,查询值的方法有两种。

随参数:

在路线先定义你的可选参数是这样的:

<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.par检查值ams.name或年龄。

通过查询参数:

不需要改变的路线,只要传递值网址和检查是这样的:

this.props.location.name or age. 

阅读这篇文章,了解在PARAMS和查询值反应:https://www.themarketingtechnologist.co/react-router-an-introduction/