Преобразование React Router в массив маршрутов всегда обновляется при изменении местоположения. Возможна ли памятка? - PullRequest
1 голос
/ 28 января 2020

Codesandbox

Привет, если я создам array of routes с React Router, который имеет HO C из <MainRoute />, который обертывает фактические <Component /> with <Main/> на каждом пути изменение <Main/> перемонтируется, и, следовательно, хук useEffect вызывается.

Можно ли перемонтировать только <Component />, а не <Main/>? Может быть, какая-то памятка?

Отображение на routes очень удобно, однако, кажется, что все изменения в местоположении меняются, что не произойдет, если я просто жестко закодирую каждый маршрут, например <MainRoute path=.. component=.. /> внутри <Switch />.

Помощь высоко ценится,

Ура

import React from "react";
import { Route, Switch, BrowserRouter, Link } from "react-router-dom";
import styled from "styled-components";

const Layout = styled.div`
  margin: auto;
  width: 0;
`;

const Main = ({ children, ...props }) => {
  React.useEffect(() => {
    console.log("API REQUEST - Called every time");
  }, []);

  return <Layout>{React.cloneElement(children, props)}</Layout>;
};

const MainRoute = ({ component: Component, ...rest }) => {
  return (
    <Route
      {...rest}
      render={props => {
        return (
          <Main path={rest.path}>
            <Component {...props} />
          </Main>
        );
      }}
    />
  );
};

export default function App() {
  return (
    <BrowserRouter>
      <Switch>
        {routes.map(({ path, component }) => (
          <MainRoute key={path} path={path} component={component} exact />
        ))}
      </Switch>
    </BrowserRouter>
  );
}

const Home = () => (
  <>
    Home <Link to="/other">Other</Link>
  </>
);
const Other = () => (
  <>
    Other <Link to="/">Home</Link>
  </>
);

const routes = [
  { path: "/", component: Home },
  { path: "/other", component: Other }
];
...