Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

javascript - React Router: strangely matched Route path props passed to its wrapper

According to React Router Doc, you can spread routeProps to make them available to your rendered Component, code below works as I expected: users will see Test if entering /test, and 404 for /test2.

If I remove {...rest}, I expected users will always see Test because the Route without a path should always match. But it still behaves the same. Can anyone tell me what's going on here?

function RouteWrapper({ children, ...rest }) {
  return (
    <Route
      {...rest} 
      render={() => children}
    />
  );
}

export default function App() {
  return (
    <Router>
      <Switch>
        <RouteWrapper path="/test">Test</RouteWrapper>
        <Route>404</Route>
      </Switch>
    </Router>
  );
}

CodesandBox Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Interesting.

It appears to be because of how the Switch component is implemented. The following snippet from the code is of particular interest:

let element, match;

React.Children.forEach(this.props.children, child => {
  if (match == null && React.isValidElement(child)) {
    element = child;

    const path = child.props.path || child.props.from;

    match = path
      ? matchPath(location.pathname, { ...child.props, path })
      : context.match;
  }
});

As you can see, the component simily looks through its children components and finds the path prop. It assumes you've passed a proper path prop to each Route component.

So it doesn't matter that you removed the path from your Route, because the Switch will take the path from your RouteWrapper component.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...