React:调用重定向到页面,并传递参数

hel*_*ght 5 javascript reactjs react-router

我正在构建我的第一个React应用程序.在我的代码中,我使用重定向到另一个页面(一个组件)

browserHistory.push(pathToMyComponent)
Run Code Online (Sandbox Code Playgroud)

我也尝试过react-router Link-element.Link元素使我能够将数据传递到目标组件,而不会显示在URL中,如下所示:

<Link to={`/myComponent/${someData}`}>
Run Code Online (Sandbox Code Playgroud)

但现在我不想创建一个链接.相反,我想在按下按钮时执行一些操作,然后使用一些计算数据重定向.我该怎么做呢?

编辑:这是我的代码.在登录页面中,用户可以执行Facebook登录.我想要的是在登录成功后将用户重定向到大厅.我想将用户ID传递到大厅.

<Router history={browserHistory} onUpdate={() => window.scrollTo(0, 0)}>
   <Route path="/" component={LoginPage}/>
   <Route path="/lobby" component={Lobby}/>
</Router>
Run Code Online (Sandbox Code Playgroud)

这是我在阅读你的答案后写的.执行此操作时,将打印日志Uncaught TypeError: Cannot read property 'context' of null

this.context.router.push({ //browserHistory.push should also work here
     pathname: '/lobby',
     state: {userid: authData.uid}
});
Run Code Online (Sandbox Code Playgroud)

Edit2:你的意思是这样的?它给出了语法错误.

class LoginPage extends React.Component {

  contextTypes = {
    router: React.PropTypes.object
  };
  constructor(props){
    super(props);
...
...
Run Code Online (Sandbox Code Playgroud)

Chr*_*ris 5

我会创建一个带有onClick事件处理程序的普通按钮来激活一个函数.在此功能中,您可以计算所需的数据,然后最终push对路由器执行操作.

例:

render() {
  return (
    ...
    <button onClick={this._handleButtonClick}>Click me</button>
    ...
  );
}

_handleButtonClick = () => {
  //calculate your data here
  //then redirect:
  this.context.router.push({ //browserHistory.push should also work here
    pathname: pathToMyComponent,
    state: {yourCalculatedData: data}
  }); 
}
Run Code Online (Sandbox Code Playgroud)

然后,您就可以从您location的数据中获取数据state.

在这里查看文档.

编辑:

this.context.router在组件的类中添加它:

static contextTypes = { 
  router: React.PropTypes.object 
} 
Run Code Online (Sandbox Code Playgroud)