简体   繁体   中英

Spread operator with React Typescript

I have a single page application with redirecting implemented as

const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
    Acc.isLoggedIn === true
        ? <Component {...props} />
        : <Redirect to={{
            pathname: '/login',
            state: { from: props.location }
        }} />
)} />

)

export { PrivateRoute };

I'm trying to update it to work something like this

interface IPrivateRouteProps {
}

interface IPrivateRouteState {
  isAuthenticated?: boolean
}

export class PrivateRoute extends React.Component<IPrivateRouteProps, IPrivateRouteState> {
constructor(props: IPrivateRouteProps) {
    super(props);

    this.state = ({ isAuthenticated: null });
}

componentDidMount() {
    Acc.isAuthenticated()
        .then(isAuthenticated => {
            this.setState({ isAuthenticated: isAuthenticated });
        });
}

render() {
    if (this.state.isAuthenticated == null) {
        return null;
    }
    else if (this.state.isAuthenticated) {
        return <Route {...rest} render={(props) => (<Component {...props} />)}/>
    }
    else {
        return <Route {...rest} render={(props) => (<Redirect to={{ pathname: '/login', state: { from: props.location } }} />)}/>
    }
}
}

How can I pass on the props using the spread operator in typescript?

Update

Needless to say, I'm not just relying to client side code for authentication.

I have already tried this but it didn't help: Spreading react props in tsx in typescript 2.3.1

rest is not defined.

Did you mean:

return <Route {...this.props} render={(props) => (<Component {...props} />)}/>

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