将 React 函数组件转换为类组件问题 [英] Converting React function component to class component issue

查看:27
本文介绍了将 React 函数组件转换为类组件问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下反应功能组件来帮助支持使用反应路由器进行身份验证所需的路由.

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 参数,但我不确定如何拉 ...rest.我是 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 函数,因此:

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 }
            }}/>
           )
         )}/>
       );
    }
}

或者,写得更具可读性:

or, written a bit more readable:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆