将React函数组件转换为类组件问题 [英] Converting React function component to class component issue
问题描述
我有以下反应功能组件来帮助支持使用react-router的身份验证所需路由。
I have the following react functional component to help support authentication required routes with react-router.
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
isAuthenticated() ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/login',
state: {from: props.location }
}}/>
)
)}/>
)
我需要转换这从功能组件到类组件,所以我可以利用React.Component的componentDidMount方法。不幸的是,我无法弄清楚如何迁移它。如果我按原样使用它,我需要复制Component和... rest参数,但我不知道该怎么做。我想我可以用this.props.component获取Component参数,但我不确定如何拉...休息。我是JSX和ES6的新手,所以我们非常感谢任何帮助或指导。
I need to convert this from a functional component to a class component so I can take advantage of the componentDidMount method of React.Component. Unfortunately I'm having trouble figuring out how to migrate this. If I take it as is I need to replicate the Component and ...rest parameters, but I'm not sure how to do that. I think I can get the Component parameter with this.props.component, but I'm not sure how to pull ...rest. I'm new to JSX and ES6 so any help or guidance would be much appreciated.
推荐答案
真的没有什么难事。功能组件是 render
函数,因此:
There isn't anything difficult really. The functional component is the render
function, therefore:
class PrivateRoute extends React.Component {
render() {
const {component: Component, ...rest} = this.props;
return (
<Route {...rest} render={props => (
isAuthenticated() ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/login',
state: {from: props.location }
}}/>
)
)}/>
);
}
}
或写得更具可读性:
class PrivateRoute extends React.Component {
render() {
const {component: Component, ...rest} = this.props;
const renderRoute = props => {
if (isAuthenticated()) {
return (
<Component {...props} />
);
}
const to = {
pathname: '/login',
state: {from: props.location}
};
return (
<Redirect to={to} />
);
}
return (
<Route {...rest} render={renderRoute}/>
);
}
}
这篇关于将React函数组件转换为类组件问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!