Javascript React/Redux身份验证路由未重定向
**注意,这在react类组件中Javascript React/Redux身份验证路由未重定向,javascript,reactjs,authentication,redux,Javascript,Reactjs,Authentication,Redux,**注意,这在react类组件中 DefaultContainer = () => { return ( <div className="app_container"> <SideNav /> <TopBar /> <Route exact path="/" component={Home} /> <Route path="/recent" compon
DefaultContainer = () => {
return (
<div className="app_container">
<SideNav />
<TopBar />
<Route exact path="/" component={Home} />
<Route path="/recent" component={Recent} />
<Route path="/AddNote" component={AddNote} />
<Route path="/ToDo" component={ToDo} />
</div>
);
};
// Check for authenticaition
AuthRoute = ({ component: Component, ...rest }) => {
return (
<Route
{...rest}
render={props => {
if (this.props.isAuthenticated) {
return <Component {...props} />;
}
else {
return (
<Redirect
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
);
}
}}
/>
);
};
render() {
return (
<BrowserRouter>
<Switch>
<Route exact path="/login" component={this.LogInContainer} />
<Route exact path="/register" component={this.RegisterContainer} />
<this.AuthRoute component={this.DefaultContainer} />
</Switch>
</BrowserRouter>
);
}
}
DefaultContainer=()=>{
返回(
);
};
//检查身份验证
AuthRoute=({component:component,…rest})=>{
返回(
{
如果(this.props.isAuthenticated){
返回;
}
否则{
返回(
);
}
}}
/>
);
};
render(){
返回(
);
}
}
我登录时,this.props.isAuthenticated设置为true。当我尝试访问“/”路由时,会被重定向回登录?但是这个.props.isAuthenticated在React开发工具中是真的吗?无法理解哪里出了问题。应该简单如下:
AuthRoute = ({ component: Component, ...rest }) => {
return (
<Route
{...rest}
render={props => {
if (props.isAuthenticated) { // <- here is the difference
return <Component {...props} />;
}
else {
return (
<Redirect
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
);
}
}}
/>
);
};
AuthRoute=({component:component,…rest})=>{
返回(
{
如果(props.isAuthenticated){//
);
};
AuthRoute看起来不像一个类,因此没有this
@colburton它是一个react组件如果你做了AuthRoute扩展react.Component…
你有一个this.props。如果你做了AuthRoute=(props)=>…
你就得到了注入的道具。