MST

星途 面试题库

面试题:React高阶组件在状态管理中的基本应用

请简述React高阶组件(HOC)的概念,并举例说明如何使用HOC在状态管理中实现数据的共享,比如有多个组件需要使用同一部分状态数据。
11.7万 热度难度
前端开发React

知识考点

AI 面试

面试题答案

一键面试

React高阶组件(HOC)概念

高阶组件(Higher - Order Component,HOC)是React中用于复用组件逻辑的一种高级技巧。它本身不是React API的一部分,而是一种基于React的组合特性而形成的设计模式。简单来说,HOC是一个函数,它接受一个组件作为参数,并返回一个新的组件。这个新组件会增强原组件的功能,比如添加额外的props、添加生命周期方法、复用状态逻辑等。

使用HOC在状态管理中实现数据共享示例

假设我们有多个组件需要共享用户登录状态等数据。

  1. 首先创建一个用于共享状态的HOC
import React from 'react';

const withSharedState = (WrappedComponent) => {
    return (props) => {
        const [user, setUser] = React.useState(null);
        const login = (newUser) => {
            setUser(newUser);
        };
        const logout = () => {
            setUser(null);
        };

        return (
            <WrappedComponent
                user={user}
                login={login}
                logout={logout}
                {...props}
            />
        );
    };
};

export default withSharedState;
  1. 然后创建需要共享状态的组件
import React from 'react';
import withSharedState from './withSharedState';

const ProfileComponent = (props) => {
    return (
        <div>
            {props.user ? (
                <div>
                    <p>Welcome, {props.user.name}</p>
                    <button onClick={props.logout}>Logout</button>
                </div>
            ) : (
                <button onClick={() => props.login({ name: 'John Doe' })}>Login</button>
            )}
        </div>
    );
};

export default withSharedState(ProfileComponent);
  1. 在另一个组件中同样使用这个HOC来共享状态
import React from 'react';
import withSharedState from './withSharedState';

const OtherComponent = (props) => {
    return (
        <div>
            {props.user && <p>User is logged in in another component: {props.user.name}</p>}
        </div>
    );
};

export default withSharedState(OtherComponent);

这样,ProfileComponentOtherComponent就通过withSharedState这个HOC共享了用户登录状态相关的数据和操作。