简体   繁体   English

React - 挂钩共享 state 用于不同的组件

[英]React - hook with shared state for different components

I have 2 components and a hook.我有 2 个组件和一个挂钩。 I want those components to share the same state through the hook.我希望这些组件通过挂钩共享相同的 state。 I created this simple codesandbox https://codesandbox.io/s/peaceful-resonance-inxbcz?file=/src/hook.js , (when you click a button it adds an item to an array), but as I see those components have separate states.我创建了这个简单的 codesandbox https://codesandbox.io/s/peaceful-resonance-inxbcz?file=/src/hook.js ,(当你点击一个按钮时,它会向数组中添加一个项目),但正如我所看到的组件有不同的状态。 Is there a simple way to use one state for all of those components?有没有一种简单的方法可以为所有这些组件使用一个 state? UP: In my live app, those components are far away from each other, on different pages. UP:在我的实时应用程序中,这些组件彼此远离,在不同的页面上。 Thanks谢谢

If you want to share you should use useState instead of useRef as useRef dont trigger component updates.如果您想共享,您应该使用 useState 而不是 useRef,因为 useRef 不会触发组件更新。

On the other hand here is an example of what i think you are trying to achieve:另一方面,这是我认为您要实现的目标的示例:

export default function App() {
  const UseCustomHook = () => {
    const [count, setCount] = useState(0);
    return [count, setCount];
  };

  const [counter, setCounter] = UseCustomHook();

  const ComponentOne = ({ setCount, count }) => (
    <button onClick={() => setCount((prev) => prev + 1)}>
      Compo 1 {count}
    </button>
  );
  const ComponentTwo = ({ setCount, count }) => (
    <button onClick={() => setCount((prev) => prev + 1)}>
      Compo 2 {count}
    </button>
  );

  return (
    <div className="App">
      <ComponentOne count={counter} setCount={setCounter} />
      <ComponentTwo count={counter} setCount={setCounter} />
    </div>
  );
}

if you need to share states trhough your app components on different levels then you should switch to useContext https://reactjs.org/docs/hooks-reference.html#usecontext如果您需要通过不同级别的应用程序组件共享状态,那么您应该切换到 useContext https://reactjs.org/docs/hooks-reference.html#usecontext

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM