【问题标题】:How do i move to a specific route anything which matches with abc/anything我如何移动到与 abc/anything 匹配的任何特定路线
【发布时间】:2019-12-19 04:08:36
【问题描述】:

我在 React Routing Concept 中遇到了一个问题,假设我有 3 个组件 home、about 和 contact 以及 about 和 contact。对于这 3 个组件,我定义了类似 abc/home(HomeComp) 的路径, abcde(aboutComp) 和 abc/abcd(contactComp)。

我如何导航到特定组件,例如 HomeComp,其路径与 abc 后跟任何内容匹配?

【问题讨论】:

  • 这是你通过路径导航到特定页面的反应路由器的概念。
  • 是的,当然它是 react 的路由概念,但这里的问题有点棘手。任何以 abc 开头的东西都必须移动到 home 组件。
  • 是的,你的 (to='' and path='') 应该匹配
  • <Route path="/" exact component={Home}/> <Route path="/abc" component={Home}/> <Route path="/abcd" exact component={List}/> <Route path="/abcd/e" component={About}/> <Route path="/contact" component={Contact}/><li><Link to="/">Home</Link></li> <li><Link to="/abc">About</Link></li> <li><Link to="/abc">Contact</Link></li> <li><Link to="/abc">List</Link></li>
  • 您面临什么问题?你说的是嵌套路由吗?

标签: reactjs routing routes react-router


【解决方案1】:

让我们以您发布问题时的示例为例。在这里,当您单击任何链接时,该链接 topath 匹配 like(to="/about" === path="/about")

const BasicExample = () => (
  <Router>
    <div>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/about">About</Link>
        </li>
        <li>
          <Link to="/contact">Contact</Link>
        </li>
      </ul>

      <hr />

      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/contact" component={Contact} />
    </div>
  </Router>
);
const About = () => (
  <div>
    <h2>About</h2>
    ....
  </div>
);
class Home extends React.Component {
  handleClick = e => {
    this.props.history.push("/about");
  };
  render() {
    return (
      <div>
        <h2>Home</h2>

        <button onClick={this.handleClick}>Click to navigate about page</button>
      </div>
    );
  }
}
const Contact = () => <h2>Contact</h2>;

Live Demo

【讨论】:

  • 是的,我已经尝试过了,它工作正常,但是如果我有 path="abc" 、 path="abcd"、 path="abcde" 和一个以 abc 开头的路径和任何应该被移动到主组件。希望这个问题很清楚
  • @AfreenKhanum 不,它不会,因为如果它有嵌套路由,你将如何分隔路由?您的服务器如何知道请求的 url?
猜你喜欢
  • 1970-01-01
  • 2019-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多