是否可以使用 React 中的 useState() 钩子在组件之间共享状态? [英] Is it possible to share states between components using the useState() hook in React?

查看:22
本文介绍了是否可以使用 React 中的 useState() 钩子在组件之间共享状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 React 中试验了新的 Hook 功能.考虑到我有以下两个组件(使用 React Hooks) -

const HookComponent = () =>{const [username, setUsername] = useState('Abrar');const [count, setState] = useState();const handleChange = (e) =>{setUsername(e.target.value);}返回 (<div><input name="userName" value={username} onChange={handleChange}/><p>{用户名}</p><p>来自钩子组件:{count}</p>

)}const HookComponent2 = () =>{const [count, setCount] = useState(999);返回 (<div><p>您点击了 {count} 次</p><button onClick={() =>setCount(count + 1)}>点击我

);}

Hooks 声称解决了组件之间共享状态逻辑的问题,但我发现 HookComponentHookComponent2 之间的状态是不可共享的.例如,HookComponent2count 的变化不会呈现 HookComponent 中的变化.

是否可以使用 useState() 钩子在组件之间共享状态?

解决方案

如果您指的是组件状态,那么钩子将无法帮助您在组件之间共享它.组件状态是组件本地的.如果您的状态存在于上下文中,那么 useContext 钩子会很有帮助.

从根本上说,我认为您误解了在组件之间共享有状态逻辑"这一行.有状态逻辑与状态不同.有状态逻辑是你所做的修改状态的事情.例如,一个组件在 componentDidMount() 中订阅了一个 store,并在 componentWillUnmount() 中取消订阅.这种订阅/取消订阅行为可以在钩子中实现,需要这种行为的组件可以直接使用钩子.

如果您想在组件之间共享状态,有多种方法可以实现,每种方法都有自己的优点:

1.提升状态

将状态提升到两个组件的共同祖先组件.

function Ancestor() {const [count, setCount] = useState(999);返回 <><DescendantA count={count} onCountChange={setCount}/><DescendantB count={count} onCountChange={setCount}/></>;}

这种状态共享方式与传统的状态使用方式没有本质的区别,钩子只是给了我们一种不同的方式来声明组件状态.

2.上下文

如果后代在组件层次结构中太深,并且您不想将状态向下传递太多层,则可以使用 上下文 API.

有一个 useContext 钩子,您可以在子组件中利用它.

3.外部状态管理解决方案

状态管理库,如 Redux 或 Mobx.然后,您的状态将存在于 React 之外的商店中,并且组件可以连接/订阅该商店以接收更新.

I was experimenting with the new Hook feature in React. Considering I have the following two components (using 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>
  );
}

Hooks claim to solve the problem of sharing stateful logic between components but I found that the states between HookComponent and HookComponent2 are not sharable. For example the change of count in HookComponent2 does not render a change in the HookComponent.

Is it possible to share states between components using the useState() hook?

解决方案

If you are referring to component state, then hooks will not help you share it between components. Component state is local to the component. If your state lives in context, then useContext hook would be helpful.

Fundamentally, I think you misunderstood the line "sharing stateful logic between components". Stateful logic is different from state. Stateful logic is stuff that you do that modifies state. For e.g., a component subscribing to a store in componentDidMount() and unsubscribing in componentWillUnmount(). This subscribing/unsubscribing behavior can be implemented in a hook and components which need this behavior can just use the hook.

If you want to share state between components, there are various ways to do so, each with its own merits:

1. Lift State Up

Lift state up to a common ancestor component of the two components.

function Ancestor() {
    const [count, setCount] = useState(999);
    return <>
      <DescendantA count={count} onCountChange={setCount} />
      <DescendantB count={count} onCountChange={setCount} />
    </>;
  }

This state sharing approach is not fundamentally different from the traditional way of using state, hooks just give us a different way to declare component state.

2. Context

If the descendants are too deep down in the component hierarchy and you don't want to pass the state down too many layers, you could use the Context API.

There's a useContext hook which you can leverage on within the child components.

3. External State Management Solution

State management libraries like Redux or Mobx. Your state will then live in a store outside of React and components can connect/subscribe to the store to receive updates.

这篇关于是否可以使用 React 中的 useState() 钩子在组件之间共享状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆