我正在尝试创建一个用于身份验证的受保护路由。文档中建议使用ProtectedRoute组件,代码如下:
interface ProtectedRouteProps {
auth: AuthState;
}
const ProtectedRoute = ({
children,
auth,
...rest
}: RouteProps & ProtectedRouteProps): JSX.Element => {
console.log(auth)
return (
<Route
{...rest}
render={(props: RouteProps) =>
auth.isAuthenticated ? children : <Redirect to={{pathname: "/signin", state: "Please sign in" }} />
}
/>
);
};
export default ProtectedRoute;
我随后使用它,并且想要展示状态(“请登录”),如果有人被重定向到登录页面。
我有一个包装组件用于处理路由:
export interface IWrapper {
auth: AuthState
}
class Wrapper extends Component<IWrapper> {
constructor(props: IWrapper){
super(props);
console.log(props)
}
render() {
return (
<div>
<BrowserRouter>
<HeaderContainer />
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route exact path="/signup">
<SignUpView />
</Route>
<ProtectedRoute auth={this.props.auth} path="/dashboard">
<DashboardContainer />
</ProtectedRoute>
</Switch>
<Route exact path="/" component={Home}></Route>
<Route exact path="/signout" component={SignUpView}></Route>
<Route exact path="/signin" component={SignIn}></Route>
</BrowserRouter>
</div>
);
}
}
const mapStateToProps = (state: AppState) => ({
auth: state.auth
})
export default connect(mapStateToProps)(Wrapper)
这是我的登录页面:
export default class SignIn<RouteComponentProps> extends Component {
constructor(props: RouteComponentProps){
super(props);
console.log(props);
}
render() {
return (
<div>
{this.props.location.state ? (
<h2>You were redirected</h2>
) : ("")}
<SignInForm />
</div>
)
}
}
在 TypeScript 编译器中,我无法使用 props.location,因为“属性‘location’不存在于类型‘Readonly<{}> & Readonly<{ children?: ReactNode; }>’中。”
对于 RouteComponentProps 的类型定义,我真的不理解这是什么意思:
export interface RouteComponentProps<Params extends { [K in keyof Params]?: string } = {}, C extends StaticContext = StaticContext, S = H.LocationState> {
history: H.History;
location: H.Location<S>;
match: match<Params>;
staticContext?: C;
}
那么问题在哪里呢?我已经尝试使用Redirect props,但也不起作用。我对Typescript是个新手,如果有人能帮忙就感激不尽了。谢谢。