2017-06-14 155 views
2

我試圖得到React-Router v4,但我遇到了一些困難。我可以創建路線並在瀏覽器中測試它們,並且它們可以正確解析,但是如果我嘗試通過編程方式將某人引導至路線,則會遇到問題。React路由器v4 - 重定向

重定向應發生在用戶點擊表中的一行後,我可以看到onClick工作正常(所以我知道回調工作)但重定向不起作用...任何想法?

import { Redirect } from 'react-router-dom'; 
export default class Table extends Component { 
... 
... 

    onClick(foo) { 
    // let path = `/booking/${foo.bar}`; 
    // console.log(path); 
    // <Route path="/booking" render={() => <BookingForm />}/>; 
    <Redirect to='/booking' />; 
    } 

... 
... 
} 

我的航線有:

const Routes =() => (
    <main> 
     <Switch> 
      <Route exact path='/' component={HomePage} /> 
      <Route exact path='/cruises' component={Cruises} /> 
      <Route exact path='/booking' component={BookingForm} /> 
     </Switch> 
    </main> 
); 

感謝

回答

3

我想下面的代碼應該解決您的問題。

import { withRouter } from 'react-router-dom'; 
class Table extends Component { 
... 
... 

    onClick(foo) { 
    let path = `/booking/${foo.bar}`; 
    this.props.history.push(path); 
    } 

... 
... 
} 

export default withRouter(Table); 
+0

多數民衆贊成在輝煌,謝謝。但是現在它在道具驗證中丟失了「歷史」。我已經按照此處列出的方法添加了PropTypes:https://github.com/yannickcr/eslint-plugin-react/issues/1109 - 但eslint仍然抱怨。 Table.PropTypes = { \t歷史:PropTypes.shape({ \t \t推:PropTypes.func.isRequired, \t}), }; – hloughrey