HOC-功能组件 [英] HOC - Functional Component

查看:47
本文介绍了HOC-功能组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之后,我已经在我的react应用中创建了一个HOC,并且它的工作正常.但是我想知道是否有一种方法可以将HOC创建为功能组件(有状态或无状态)???因为给定的示例是基于类的组件.

I have already created a HOC in my react app following this, and its working fine. However i was wondering if there is a way to create a HOC as functional component(With or without state)??? since the given example is a class based component.

试图在网上找到同样的东西,但什么也没得到.不知道那是否有可能?还是做正确的事?

Tried to find the same over web but couldn't get anything. Not sure if thats even possible?? Or right thing to do ever??

任何线索都将不胜感激:)

Any leads will be appreciated :)

推荐答案

例如,您可以肯定地创建一个功能性的无状态组件,该组件接受该组件作为输入,并返回其他一些组件作为输出;

Definitely you can create a functional stateless component that accepts component as an input and return some other component as an output, for example;

  1. 您可以创建一个PrivateRoute组件,该组件接受一个组件作为prop值,并根据用户是否通过身份验证返回其他一些组件.
  2. 如果用户未通过身份验证(从上下文存储中读取),则可以使用< Redirect to ='/login'/> 将用户重定向到登录页面,否则返回以prop并将其他prop发送到该组件< Component {... props}/>
  1. You can create a PrivateRoute component that accepts a Component as a prop value and returns some other Component depending on if user is authenticated or not.
  2. If user is not authenticated(read it from context store) then you redirect user to login page with <Redirect to='/login'/>else you return the component passed as a prop and send other props to that component <Component {...props} />

App.js

const App = () => {
  return (
      <Switch>
        <PrivateRoute exact path='/' component={Home} />
        <Route exact path='/about' component={About} />
        <Route exact path='/login' component={Login} />
        <Route exact path='/register' component={Register} />
      </Switch>
  );
}

export default App;

PrivateRoute.jsx

import React, { useContext , useEffect} from 'react';
import { Route, Redirect } from 'react-router-dom'
import AuthContext from '../../context/auth/authContext'

const PrivateRoute = ({ component: Component, ...rest }) => {
  const authContext = useContext(AuthContext)
  const { loadUser, isAuthenticated } = authContext
  useEffect(() => {
    loadUser()
    // eslint-disable-next-line
  }, [])
  if(isAuthenticated === null){
    return <></>
  }
  return (
    <Route {...rest} render={props =>
      !isAuthenticated ? (
        <Redirect to='/login'/>
      ) : (
        <Component {...props} />
      )
    }
    />
  );
};
export default PrivateRoute;

高阶组件不必是类组件,它们的目的是根据某种逻辑将一个组件作为输入并返回一个组件作为输出.

Higher Order Components does not have to be class components, their purpose is to take a Component as an input and return a component as an output according to some logic.

这篇关于HOC-功能组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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