开发者问题收集

路由渲染错误组件,ReactJS

2020-08-17
219

我尝试在调用 URL /folders/xy 后访问 FolderDetail 组件。我总是获取位于 /folders 中的 Folders 组件,而不是获取 FolderDetail 组件...请帮忙。

import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';

    function App() {
      return (
        <BrowserRouter>
          <div className="App">
            <Navigation />
            <Switch>
              <Route path="/" component={Home} exact />
              <Route path="/folders" component={Folders} />
              <Route path="/folders/:id" component={FolderDetail} />
              <Route path="/login" component={Login} />
            </Switch>
          </div>
        </BrowserRouter>
      );
    }
    
    export default App;
2个回答

您应该将 exact 添加到所有 Routes 组件,这是一个有效的 codesandbox :

const App = () => {
  return (
    <BrowserRouter>
      <div className="App">
        <Navigation />
        <Switch>
          <Route exact path="/" component={Home} />
          <Route exact path="/folders" component={Folders} />
          <Route exact path="/folders/:id" component={FolderDetail} />
        </Switch>
      </div>
    </BrowserRouter>
  );
};
Lafi
2020-08-17

交换机会采用第一个匹配的路线,因此您需要像这样重新排序您的路线,(还需添加 exact

 <Switch>
     <Route exact path="/folders/:id" component={FolderDetail} />
     <Route exact path="/folders" component={Folders} />
     <Route exact path="/login" component={Login} />
     <Route exact path="/" component={Home} exact />
 </Switch>

始终将更具体的路线放在第一位。

Shmili Breuer
2020-08-17