使用React Router路由到不同组件以进行类似路由

时间:2019-11-21 05:58:48

标签: reactjs react-router

我正在尝试路由到不同的组件,但是最后一条路由正在捕获它

<Switch>
    <Route path="/users" exact strict component={Users}/> // this one works fine
    <Route path="/users/new" exact strict component={NewUser}/> // this one is not. the next route is catching it...
    <Route path="/users/:userId" exact strict component={UserDetails}/>
</Switch>

感谢您的帮助。

4 个答案:

答案 0 :(得分:1)

我认为如果您重新布置路线会起作用,这是我的想法

<Switch>
    <Route exact path="/users/new" component={NewUser}/>
    <Route path="/users/:userId" component={UserDetails}/>
    <Route path="/users" component={Users}/> // this one works fine
</Switch>

对我有用

您可以尝试一下,希望它能起作用

答案 1 :(得分:0)

嗨,这是我的基本路线,对我来说,效果很好。

谢谢

import React, { Component } from "react";
import "./App.css";
import login from "./login";
import Home from "./Home";
import GoogleApi from "./GoogleApi";
import State from "./State";
import { BrowserRouter, Router, Route, Link, Switch } from "react-router-dom";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    return (
      <div>
        <BrowserRouter>
          <Switch>
            <Route exact path="/" component={login} />
            <Route path="/googleapi" component={GoogleApi} />
            <Route path="/home" component={Home} />
            <Route path="/state" component={State} />
          </Switch>
        </BrowserRouter>
      </div>
    );
  }
}

export default App;

答案 2 :(得分:0)

重新排列您的路线,效果很好。我已经在我的项目中对其进行了测试

    <Route path="/users/new" exact  component={NewUser}/> 
    <Route path="/users/:userId" exact  component={UserDetails}/>
    <Route path="/users" exact  component={Users}/> 

希望这会对您有所帮助。如果您有任何问题,请告诉我。

答案 3 :(得分:0)

<BrowserRouter>
          <Switch>
            <Route exact path="/users" component={Users} />
            <Route path="/users/new" component={NewUser} />
            <Route path="/users/:userId" component={UserDetails} />
          </Switch>
        </BrowserRouter>