是否有一种方法可以在同一react元素内的挂钩调用之间进行交互

时间:2019-08-08 21:39:50

标签: javascript reactjs react-hooks

问题

在同一渲染调用中,是否有任何方式可以在钩子调用之间进行交互?要使钩子在每次调用时都可以访问相同的值。例如,是否可以实现useRandom()钩子,该钩子将生成随机值,然后即使在同一渲染周期内也将在每次调用时返回相同的值。

可能但不是理想的解决方案

我唯一的解决方案是用一些上下文包装组件,并在每个要进行交互的钩子调用上使用此上下文。但是迫使我为每个组件创建两个额外的节点(要使用的上下文和内部的另一个上下文,以防止嵌套组件使用相同的上下文)。我可以为此创建HoC / renderProp,但是这两个附加上下文仍然存在。

示例

上下文和钩子

const InteractContext = React.createContext();

const useRandom = () => {
  const context = useContext(InteractContext);

  if (!context.value) {
    context.value = Math.random();
  }

  return context.value;
}

使用挂钩的组件

const MyComponent = () => {
  const random1 = useRandom();
  const random2 = useRandom();

  return (
    // to prevent using this value by nested components
    <InteractContext value={ null }>
      {random1} === {random2}
    </InteractContext>
  );
}

渲染组件

render(
  <>
    <InteractContext value={{}}>
      <MyComponent />
    </InteractContext>,
    <InteractContext value={{}}>
      <MyComponent />
    </InteractContext>
  </>,
  document.getElementById('root')
);

预期结果

我希望看到这种格式的行:

<some random number> === <the same number>
<another random number> === <the same random number>

这是一个示例:

0.123456789 === 0.123456789
0.987654321 === 0.987654321

1 个答案:

答案 0 :(得分:1)

也许是关闭?

 const useRandomness = () => (r => () => r)(Math.random());

 // inside the component:
  const useRandom = useRandomness();
  useRandom() === useRandom();

或在以下位置传递该共享值:

  const useRandom = v => v;

  // inside the component:
 const random = Math.random();

 useRandom(random) === useRandom(random)