React Router Switch 不渲染特定组件

汤姆汉森

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

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

// 浏览器路由器

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?

比伦德拉

是的,这肯定会先返回

<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} />

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章