面试题答案
一键面试React高阶组件(HOC)概念
高阶组件(Higher - Order Component,HOC)是React中用于复用组件逻辑的一种高级技巧。它本身不是React API的一部分,而是一种基于React的组合特性而形成的设计模式。简单来说,HOC是一个函数,它接受一个组件作为参数,并返回一个新的组件。这个新组件会增强原组件的功能,比如添加额外的props、添加生命周期方法、复用状态逻辑等。
使用HOC在状态管理中实现数据共享示例
假设我们有多个组件需要共享用户登录状态等数据。
- 首先创建一个用于共享状态的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;
- 然后创建需要共享状态的组件
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);
- 在另一个组件中同样使用这个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);
这样,ProfileComponent
和OtherComponent
就通过withSharedState
这个HOC共享了用户登录状态相关的数据和操作。