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/