首页 文章

React Router Switch不呈现特定组件

提问于
浏览
0

我有一个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?

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' so / new和/:id是相同的参数 .

    所以最后'CityList'将返回

    你可以这样定义

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

    很确定你的路线不起作用,因为你也使用/ locations /:id将params与/ locations / new匹配,然后'new'变为Id param .

    尝试改变这个

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

    对于这样的事情

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

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

相关问题