面试题答案
一键面试思路
- 创建自定义 Hook:将需要共享的状态逻辑封装在一个自定义 Hook 中。这个 Hook 负责管理状态以及相关的更新函数。
- 在多个组件中使用:不同的组件通过调用这个自定义 Hook 来获取共享状态和更新函数,从而实现状态共享和同步更新。
基本步骤
- 定义自定义 Hook:在自定义 Hook 中使用
useState
来管理共享状态,返回状态值和更新函数。 - 在组件中引入并使用:在需要共享状态的组件中引入自定义 Hook,调用它获取状态和更新函数,然后在组件中使用这些值。
代码示例
import React, { useState } from 'react';
// 自定义 Hook
const useSharedCounter = () => {
const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
return { count, increment, decrement };
};
// 第一个组件
const ComponentA = () => {
const { count, increment } = useSharedCounter();
return (
<div>
<p>Component A: {count}</p>
<button onClick={increment}>Increment in A</button>
</div>
);
};
// 第二个组件
const ComponentB = () => {
const { count, decrement } = useSharedCounter();
return (
<div>
<p>Component B: {count}</p>
<button onClick={decrement}>Decrement in B</button>
</div>
);
};
const App = () => {
return (
<div>
<ComponentA />
<ComponentB />
</div>
);
};
export default App;
在上述代码中,useSharedCounter
是自定义 Hook,它管理一个计数器 count
以及 increment
和 decrement
方法。ComponentA
和 ComponentB
都使用这个自定义 Hook,使得它们之间的计数器状态能够同步更新。