2017-06-14 152 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