我有一个React应用程序,当前正在使用react-router@4.2.0,而且当URL更改时我很难渲染特定组件。
当我尝试访问/locations/new
时,它返回CityList组件中的PropTypes错误。我已经尝试将exact
添加到LocationsWrapper中的Route组件,然后添加Main配置,但是,这会影响其他路由 - 例如/locations
变为空。
// 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?
答案 0 :(得分:0)
非常确定您的路线无法正常工作,因为您还将带有/ locations / new的params与/ locations /:id匹配,以便&#39; new&#39;成为Id param。
尝试更改此
<Route path="/locations/new" component={CreateLocation} />
这样的事情
<Route path="/locs/new" component={CreateLocation} />
只是建议希望这可能有所帮助
答案 1 :(得分: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} />