简体   繁体   中英

Redirect won't work with react-router v4

I got this warning

Warning: You should not use <Route component> and <Route render> in the same route; <Route render> will be ignored

Not sure it's causing the Redirect to fail, but my code below just won't work, it's fine if this.isAuth is true, but not with <Redirect />

https://codesandbox.io/s/5xm202p1j4

render() {
    const { Component: component, ...rest } = this.props;

    return (
      <Route
        {...rest}
        render={props =>
          this.isAuth === false ? (
            <Component {...props} />
          ) : (
            <Redirect
              to={{
                pathname: "/login"
              }}
            />
          )
        }
      />
    );
  }

You have destructured your props incorrectly, it should be const { component: Component, ...rest } = this.props;

The reason that it was giving you the warning was because you tried to destructure Component with uppercase C from props whereas you pass component as props to the authRoute, and not since Component is now present in props the rest params contains the component props which is passed down to the Route .

render() {
    const { component: Component, ...rest } = this.props;

    return (
      <Route
        {...rest}
        render={props =>
          this.isAuth === false ? (
            <Component {...props} />
          ) : (
            <Redirect
              to={{
                pathname: "/login"
              }}
            />
          )
        }
      />
    );
  }

Working sandbox

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM