2017-05-25 74 views
1

我是新的reactjs - 如果我打到一個子頁面上的錯誤頁面 - 因爲URL是錯誤的 - 我正在尋找一種方法來重定向頁面到另一個。ReactJs - 重定向url

所以DE/dienstleistungen/isdfisf - 拼寫錯誤 重定向到DE/dienstleistungen

我試圖寫一個函數來處理這個問題,但沒有運氣

if (!lang.serviceIntro[0][service]) { 
    console.log('undefined', this) 
    this.context.router.push('/de/dienstleistungen') 
    } 

失敗上下文類型:無效上下文router類型object提供給PlainHeader,預計function

回答

0

你使用react-router嗎?如果使用了哪個版本的話? 檢出https://reacttraining.com/react-router/web/api/history這是目前在v4上。這是我的代碼

class App extends Component { 
    componentDidMount() { 
     let token = ... // achieve token 
     if (!token) { 
      this.props.history.push('/login'); 
     } 
    } 

    render() { 
     .... 
    } 
} 

我的代碼在主頁檢查,如果未驗證將重定向到登錄頁面以編程方式。道具this.props.history將被反應路由器通過。 查看上面的文檔以獲取更多信息。希望它能幫助

0

由於錯誤消息說,你應該聲明contextTypes.router爲對象,路由器是在舊版本的功能

static contextTypes = { 
    router: PropTypes.object.isRequired 
}