在使用反应钩子渲染之前调度 redux 动作

Dispatch redux action before render with react hooks

所以,正如标题所说:我们如何在渲染组件之前分派 redux 操作?

我有一个特定的情况,我需要在组件呈现之前清除一些共享状态块(在这种情况下显示“正在加载...”),这是通过调度 redux 操作完成的。

现在,如果我用 useEffect 发送它,我会先显示闪烁的 stale/old 数据,然后显示“正在加载...”。

到目前为止,我看到了 2 种解决方法:

  1. useLayoutEffect - 我喜欢它,但不确定它是否是一个好习惯
  2. 重新定义 redux 模型 - 我想避免的那个加上它听起来有点奇怪

我可能会创建自定义 Fetcher 钩子,但这不会把它带回 hocs/wrapper 地狱的境界吗?

我只想在第一次渲染之前做点什么。

useEffectuseLayoutEffect的区别是后者在初始渲染后同步执行:

The signature is identical to useEffect, but it fires synchronously after all DOM mutations. Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside useLayoutEffect will be flushed synchronously, before the browser has a chance to paint.

如果闪烁是 useEffect 的唯一问题,并且 useLayoutEffect 消失,则应使用后者。