React Router Switch不呈现特定组件

问题描述 投票:0回答:2

我有一个React应用程序,当前正在使用[email protected],我正在努力在URL更改时呈现特定组件。

当我尝试访问/locations/new时,它返回CityList组件中的PropTypes错误。我已经尝试将exact添加到LocationsWrapper中的Route组件,然后添加Main配置,但是,这会影响其他路由 - 例如/locations变为null。

// BrowserRouter

import React from "react";
import { render } from "react-dom";
import { BrowserRouter } from "react-router-dom";
import { Provider } from "react-redux";

import store from "./store";
import Navbar from "./components/Core/Navbar";
import Routes from "./config/routes";

render(
  <Provider store={store}>
    <BrowserRouter>
      <div style={{ backgroundColor: "#FCFCFC" }}>
        <Navbar />
        <Routes />
      </div>
    </BrowserRouter>
  </Provider>,
  document.getElementById("root")
);

//路由器配置 - (路由)

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

import Home from "../components/Home";
import Locations from "../components/Locations";
import CityList from "../components/CityList";
import CreateLocation from "../components/CreateLocation";
import Locale from "../components/Locale/index";
import Profile from "../components/Profile";
import NoMatch from "../components/Core/NoMatch";

import requireAuth from "../components/Core/HOC/Auth";

const LocationsWrapper = () => (
  <div>
    <Route exact path="/locations" component={Locations} />
    <Route path="/locations/new" component={CreateLocation} />
    <Route path="/locations/:id" component={CityList} />
  </div>
);

const Main = () => (
  <main>
    <Switch>
      <Route exact path="/" component={requireAuth(Home)} />
      <Route path="/locations" component={LocationsWrapper} />
      <Route path="/locale/:id" component={Locale} />
      <Route path="/profile" component={requireAuth(Profile, true)} />
      <Route component={NoMatch} />
    </Switch>
  </main>
);

export default Main;

我是否最好完全避免使用<Switch>并为未定义的路由实现新方法 - 例如404s?

javascript node.js reactjs react-router
2个回答
0
投票

是的,这肯定会先回归

<Route path="/locations/:id" component={CityList} />

在react-router 4中没有索引路由的概念,它将检查每条路由,因此在您的定义路由中是相同的

<Route path="/locations/new" component={CreateLocation} />
<Route path="/locations/:id" component={CityList} />

两条路径都是相同的'/location/new''/location/:id'所以/ new和/:id是相同的参数。

所以最后'CityList'将返回

你可以这样定义

<Route path="/locations/create/new" component={CreateLocation} />
<Route path="/locations/list/:id" component={CityList} />

0
投票

很确定你的路线不能正常工作,因为你也将params与/ locations / new匹配/ locations /:id,那么'new'就变成了Id param。

尝试改变这个

   <Route path="/locations/new" component={CreateLocation} />

对于这样的事情

   <Route path="/locs/new" component={CreateLocation} />

只是一个建议希望这可能会有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.