2016-10-11 96 views
0

作爲在瀏覽器中輸入http://localhost:3000/ui/?goto=/ui/entity/e2的示例,我想轉到實體組件e2。如何根據URL參數轉到React的特定頁面

這是我的路由器:

<Route path="/ui/" component={App}> 
     <IndexRoute component={EntitiesPage} /> 
     <Route  component={Entity}  path="entity/:id" /> 
     <Route  component={NotFound}  path="*" /> 
</Route> 

這是應用程序組件:

import React from 'react' 

const App = React.createClass({ 
    render() { 
     let gotoUrl = this.props.location.query.goto; 
     if (gotoUrl) { 
      // go here: gotoUrl; 
     } else { 
      return (
       <div className="App"> 
        {this.props.children} 
       </div> 
      ) 
     } 
    } 
}) 
export default App 

this.context是空的。 this.props有:

  • 歷史
  • 位置
  • 路線
  • routeParams(空)
  • 路線

更新: 我已經結束了使用此:

import React from 'react' 
import { withRouter } from 'react-router' 

const App = React.createClass({ 
    componentWillMount() { 
     let gotoUrl = this.props.location.query.goto; 
     if (gotoUrl) { 
      this.props.router.replace(gotoUrl); 
     } 
    }, 

    render() { 
     return (
      <div className="App"> 
       {this.props.children} 
      </div> 
     ); 
    } 
}) 
export default withRouter(App) 

回答

0

一兩件事,可能會絆倒您是render應該沒有副作用

「副作用」是任何改變您的應用程序*中發生的事情:更新狀態,進行AJAX調用,或者在這種情況下,更改頁面位置。 render方法應該只從讀取組件的當前狀態,然後返回值

因爲您已經在使用React.createClass,所以處理此問題的最佳方法是添加React專門處理的單獨方法:componentWillMount。我建議你在這裏放置你的「重定向」邏輯。

爲了正確更改頁面位置,您需要訪問瀏覽器歷史記錄對象,該對象可以操作react-router。您可以從react-router庫本身導入這一點,並直接調用它的方法:

// At top of file 
import { browserHistory } from 'react-router' 

// Then, in your component: 
componentWillMount() { 
    let gotoUrl = this.props.location.query.goto; 
    if (gotoUrl) { 
     // NOTE: this may have security implications; see below 
     browserHistory.push(gotoUrl); 
    } 
} 

來源:documentation

我建議,而不是使用query.goto,而是選擇一個可以很容易驗證的參數,例如實體ID本身(一個簡單的正則表達式可以確保它是有效的)。否則,不道德的用戶可能會向其他用戶發送鏈接,導致他們訪問他們不認爲的網頁。

*注意:有更嚴格的「副作用」的定義,但這對React開發非常有用。

0

您應該使用browserHistory

import { browserHistory } from 'react-router'; 
... 
if (gotoUrl) { 
    browserHistory.push(gotoUrl) 
} 

讓我知道這是否正常工作

相關問題