【发布时间】:2019-03-17 03:17:59
【问题描述】:
我需要将此基于功能的 Component 转换为基于类的 Component 并创建一个 PrivateAuth Component 。 这是 PrivateAuth 功能组件。
function PrivateRoute({ component: Component, ...rest }) {
return (
<Route
{...rest}
render={props =>
fakeAuth.isAuthenticated ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
)
}
/>
);
}
这是我尝试过的基于类的组件。
class PrivateRoute extends React.Component{
render(){
console.log('this.props',this.props);
const{ component: Component, ...rest } =this.props;
return(
<Route
render={props =>
fakeAuth.isAuthenticated ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
)
}
/>
);
}
}
我得到了错误 超过最大更新深度。
【问题讨论】:
-
你没有像在你的函数组件中那样在
Route上传播休息:{...rest}。否则它们看起来是一样的。您确定功能组件版本有效吗? -
有什么问题?我刚刚尝试了您提供的解决方案并且它有效。不要忘记将
{...rest}也分配给<Route>。这可能是您的任何组件中的问题,或者只是您声明路由器的方式。如果它来自另一个组件,您可以检查错误吗?
标签: javascript reactjs