【发布时间】:2018-08-11 14:00:16
【问题描述】:
我有一个当前使用 react-router@4.2.0 的 React 应用程序,当 URL 更改时,我正在努力渲染特定组件。
当我尝试访问 /locations/new 时,它会返回来自 CityList 组件的 PropTypes 错误。我尝试将 exact 添加到 LocationsWrapper 中的 Route 组件中,然后添加到 Main 配置中,但是,这会影响其他路由 - 例如 /locations 变为 null。
// 浏览器路由器
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")
);
// 路由器配置 - (Routes)
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