【发布时间】:2020-02-18 19:53:00
【问题描述】:
我正在尝试为身份验证创建受保护的路由。我有一个文档中建议的 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>
)
}
}
打字稿编译器说我不能做 props.location,因为“类型 'Readonly & Readonly' 上不存在属性 'location'。”
我真的不明白这是什么意思。在 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;
}
那么问题是什么?我试过使用重定向道具,但这也不起作用。我是 Typescript 的 n00b,所以如果有人能提供帮助,我将不胜感激。谢谢。
【问题讨论】:
标签: reactjs typescript router