【问题标题】:How Can I route From One page to another when its route are in different file当它的路由在不同的文件中时,如何从一个页面路由到另一个页面
【发布时间】:2018-09-13 08:08:46
【问题描述】:

我正在使用 React.js 我的路由文件如下 -> app.js 主要有 3 条路由

  • 路线 1(内部有更多路线)

<Switch>
      <Route path='/auth' component={Auth}/>
      <Route path='/panel' component={Panel}/>
      <Route path='/show' component={Show}/>
    </Switch>
  • 路线 2(内部有更多路线)

<Switch>
      <Route exact path='/panel/products' component={Products}/>
      <R<Route exact path='/panel/products1' component={Products1}/>
      <Route exact path='/panel/products2' component={Products2}/>
</Switch>
  • 路线 3(内部有更多路线)

<Switch>
  <Route exact path='/show/message' component={Message}/>
</Switch>

现在,当我尝试使用 this.props.push('/show/message') 从路线 2 子路线跳转到路线 3 时,它不起作用 它只是将我重定向到 Routes 2 的默认路由

当我在路线 2 内路由时,它工作正常 ,有什么解决办法吗???

【问题讨论】:

  • 您能展示一些您的代码并告诉我们您当前使用的 react-router 版本吗?
  • "react-router-dom": "4.3.1",

标签: reactjs react-router-dom


【解决方案1】:

您确定使用this.props.push() 调用了push() 方法吗?无论如何,尝试用withRouter HOC 包装你的组件,这样它就可以接收诸如matchlocationhistory 之类的道具。然后,使用 history 属性将新条目推送到历史堆栈。 例如,使用你的 Products2 组件,试试这个代码:

import React from 'react';
import { withRouter } from 'react-router';
class Products2 extends Component {
   render(){
     const { match, location, history } = this.props;
     return (
         <button onClick={() => history.push('/show/message')}>Redirect to third route</button>
     );
   }
}

export default withRouter(Products2);

您可以尝试的另一种方法是将父路由的道具传递给子路由。

import React from 'react';
import { Route, Switch } from 'react-router-dom';
//import here your child components

class Panel extends Component {
   render(){
     return (
     <Switch>
        <Route exact path='/panel/products' render={() => <Products parentProps={this.props} />}/>
        <Route exact path='/panel/products1' component={Products1}/>
        <Route exact path='/panel/products2' component={Products2}/>
     </Switch>
     );
   }
}

export default Panel;

然后在Products组件中,使用this.props.parentProps.history.push('/show/message')

【讨论】:

  • 我尝试了,但它仍然将我重定向到默认路由,当我评论我的默认路由时,URL 更改为'XXX/show/message',但它不会重定向我,直到我按 Enter
  • 我添加了另一种方法。看看吧。
猜你喜欢
  • 2021-01-06
  • 1970-01-01
  • 1970-01-01
  • 2021-10-15
  • 2011-03-06
  • 2019-04-13
  • 1970-01-01
  • 1970-01-01
  • 2021-09-12
相关资源
最近更新 更多