加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – 如何使用TypeScript和React-Router 4重写受保护的路

发布时间:2020-12-15 05:06:18 所属栏目:百科 来源:网络整理
导读:我试图创建一个 PrivateRoute如使用TypeScript在react-router documents中描述的那样.谁能帮我吗? react-router文件中的privateRoute: const PrivateRoute = ({ component: Component,...rest }) = ( Route {...rest} render={props = ( fakeAuth.isAuthen
我试图创建一个< PrivateRoute>如使用TypeScript在react-router documents中描述的那样.谁能帮我吗?

react-router文件中的privateRoute:

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

下面是我的TypeScript版本(它不起作用):

const PrivateRoute = (theProps: { path: string,component: React.SFC<RouteComponentProps<any> | undefined> | React.ComponentClass<RouteComponentProps<any> | undefined> }) => {
    return <Route path={theProps.path} render={props => (
        fakeAuth.isAuthenticated ? (
            <React.Component {...theProps} /> <!-- **** It will raise error *** -->
        ) : (
                <Redirect to={{
                    pathname: '/',state: { from: props.location }
                }} />
            )
    )} />
}

< React.Component {... thisProps} />是不正确的.错误是:NodeInvocationException:inst.render不是函数
TypeError:inst.render不是函数

错误可能与输入中的输入和隐式返回有关.解决这个问题后,你最终会得到这样的结果:
const PrivateRoute = ({component,isAuthenticated,...rest}: any) => {
    const routeComponent = (props: any) => (
        isAuthenticated
            ? React.createElement(component,props)
            : <Redirect to={{pathname: '/login'}}/>
    );
    return <Route {...rest} render={routeComponent}/>;
};

这个组件可以像这样使用:

<PrivateRoute
    path='/private'
    isAuthenticated={this.props.state.session.isAuthenticated}
    component={PrivateContainer}
/>

上面的解决方案有一些缺点.其中一个原因是您失去了类型安全性.

可能扩展Route组件是更好的主意.

import * as React from 'react';
import {Redirect,Route,RouteProps} from 'react-router';

export interface ProtectedRouteProps extends RouteProps {
    isAuthenticated: boolean;
    authenticationPath: string;
}

export class ProtectedRoute extends Route<ProtectedRouteProps> {
    public render() {
        let redirectPath: string = '';
        if (!this.props.isAuthenticated) {
            redirectPath = this.props.authenticationPath;
        }

        if (redirectPath) {
            const renderComponent = () => (<Redirect to={{pathname: redirectPath}}/>);
            return <Route {...this.props} component={renderComponent} render={undefined}/>;
        } else {
            return <Route {...this.props}/>;
        }
    }
}

所以你可以使用这样的组件:

const defaultProtectedRouteProps: ProtectedRouteProps = {
    isAuthenticated: this.props.state.session.isAuthenticated,authenticationPath: '/login',};

<ProtectedRoute
    {...defaultProtectedRouteProps}
    exact={true}
    path='/'
    component={ProtectedContainer}
/>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读