React Router Switch不呈现特定组件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React Router Switch不呈现特定组件相关的知识,希望对你有一定的参考价值。
我有一个React应用程序,当前正在使用react-router@4.2.0,我正在努力在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?
是的,这肯定会先回归
<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} />
很确定你的路线不能正常工作,因为你也将params与/ locations / new匹配/ locations /:id,那么'new'就变成了Id param。
尝试改变这个
<Route path="/locations/new" component={CreateLocation} />
对于这样的事情
<Route path="/locs/new" component={CreateLocation} />
只是一个建议希望这可能会有所帮助
以上是关于React Router Switch不呈现特定组件的主要内容,如果未能解决你的问题,请参考以下文章
react-router v4.2.2 开关不工作;始终显示主要组件
尝试导入错误:“Switch”未从“react-router-dom”导出
React Router 5 不使用查询参数/状态重定向(剥离查询参数/状态)