【发布时间】:2017-11-07 07:30:57
【问题描述】:
所以我知道其他人也问过类似的问题,但情况略有不同。我正在尝试检查用户在访问私有路由时是否经过身份验证,并且我已经像这样设置了我的私有路由包装器:
export const PrivateRoute = ({ component: Component, store: store, ...rest }: { component: any, store: Store<ApplicationState>, path: any }) => (
<Route {...rest} render={(props:ReduxRouteComponentProps) => (
store.getState().authenticationState.authenticated ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
);
PrivateRoute 从根组件获取 store 作为 prop 传递。
调试时,我收到store.getState is not a function 错误,但是当我将鼠标悬停在 store 参数上时,我可以看到至少 Chrome 调试器认为确实如此。
这到底是怎么回事?
编辑:PrivateRoute 用法
有人要求我显示使用私有路由的位置——这里有一些 sn-ps:
// Navigation Frame
export class NavigationFrame extends React.Component<INavigationFrameProps, {}> {
render() {
console.log(this)
return <Router>
<div className="navigation-frame">
<Route exact path="/" component={Splash}/>
<Route exact path="/register" component={RegistrationForm}/>
<Route path="/signin" component={SignInContainer}/>
<PrivateRoute store={this.props.store} path="/i" component={AuthenticatedView}/>
</div>
</Router>;
}
}
和提供者标签...
// main.tsx
ReactDOM.render(
<Provider store={store}>
<App name="my-app" />
</Provider>,
document.getElementById("react-app")
);
编辑:问我为什么不将商店映射到道具...
你的意思是这样的吗?以下为我抛出错误,说 PrivateRoute 是 connect 的不兼容类型
let getAuthState = (state: AuthenticationState) => {
return state;
}
const mapDispatchToProps = (dispatch:any) => {
return {}
}
const mapStateToProps = (state: ApplicationState) => {
return {
authState: getAuthState(state.authenticationState)
}
}
export const PrivateRouteContainer = connect(
mapStateToProps,
mapDispatchToProps
)(PrivateRoute);
【问题讨论】:
-
能贴出使用
PrivateRoute的代码吗? -
您没有将
authenticateState映射到组件道具的任何原因?你也检查过 react 开发工具吗? -
this.state.authenticationState 不起作用吗?
标签: reactjs redux react-redux react-router-v4