代码之家  ›  专栏  ›  技术社区  ›  Connell.O'Donnell

带有React Typescript的Spread运算符

  •  0
  • Connell.O'Donnell  · 技术社区  · 6 年前

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

    )

    export { PrivateRoute };
    

    我想把它更新成这样

    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 } }} />)}/>
        }
    }
    }
    

    如何使用typescript中的spread运算符传递道具?

    不用说,我不仅仅依赖客户端代码进行身份验证。

    我已经试过了,但没用: Spreading react props in tsx in typescript 2.3.1

    1 回复  |  直到 5 年前
        1
  •  0
  •   jonathangoodman    6 年前

    rest 未定义。

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