我有以下反应功能组件来帮助支持使用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的新手,所以我们非常感谢任何帮助或指导.
解决方法
真的没什么难的.功能组件是渲染功能,因此:
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}/> ); } }