我在试验 React 中的 Hook 新功能。考虑到我有以下两个组件(使用 React Hooks)-
const HookComponent = () => {
const [username, setUsername] = useState('Abrar');
const [count, setState] = useState();
const handleChange = (e) => {
setUsername(e.target.value);
}
return (
<div>
<input name="userName" value={username} onChange={handleChange}/>
<p>{username}</p>
<p>From HookComponent: {count}</p>
</div>
)
}
const HookComponent2 = () => {
const [count, setCount] = useState(999);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Hook 声称解决了组件之间共享状态逻辑的问题,但是我发现 HookComponent
和 HookComponent2
之间的状态是不可共享的。例如,HookComponent2
中 count
的变化并不表示 HookComponent
的变化。
是否可以使用 useState()
钩子在组件之间共享状态?