小编bel*_*a53的帖子

在 useRef() 中存储回调

下面是一个可变 ref 的示例,该示例存储来自Overreacted 博客的当前回调:

function useInterval(callback, delay) {
  const savedCallback = useRef();

  // update ref before 2nd effect
  useEffect(() => {
    savedCallback.current = callback; // save the callback in a mutable ref
  });

  useEffect(() => {
    function tick() {
      // can always access the most recent callback value without callback dep 
      savedCallback.current(); 
    }

    let id = setInterval(tick, delay);
    return () => clearInterval(id);
  }, [delay]);
}
Run Code Online (Sandbox Code Playgroud)

然而,React Hook FAQ 指出不推荐使用该模式:

另请注意,此模式可能会导致并发模式出现问题。[...]

在任何一种情况下,我们都不推荐这种模式,只是为了完整起见在这里展示它。

我发现这种模式对于回调非常有用,但我不明白为什么它会在 FAQ 中出现危险信号。例如,客户端组件可以使用 …

javascript reactjs react-ref react-hooks react-concurrent

14
推荐指数
1
解决办法
1194
查看次数

我可以依赖组件中的 useEffect 顺序吗?

考虑以下模式:

const Comp = ({ handler })=> {
  // handler is some callback of the form ( ) => void
  useSomeHook(handler);
  //...
}

function useSomeHook(cb) {
  const ref = useRef()

  useEffect(() => {
    ref.current = cb; // update ref before second useEffect
  })

  useEffect(() => {
    // use the current (most recent) ref value
    const iv = setInterval(() => { ref.current() }, 3000) 
    return () => { clearInterval(iv) };
  }, []) // run only after first render
}
Run Code Online (Sandbox Code Playgroud)

问:我可以依靠的事实,首先useEffect …

reactjs react-hooks

8
推荐指数
1
解决办法
1629
查看次数

React 是否保证 `props` 对象引用保持稳定?

最近我看到类似于以下人为示例的代码:

const MyComp = props => {
  const [prevProps, setPrevProps] = useState(props)

  if (props !== prevProps) {
    setPrevProps(props);
    // do something else...
  }
}
Run Code Online (Sandbox Code Playgroud)

该组件使用某种派生状态来记住之前的道具。如果 的内存位置发生props了变化 ( props !== prevProps),它将新的 props 同步到useState

是的,这没有多大意义,但我的观点是:React 是否做出任何保证,即 的对象引用props保持不变,因为没有包含的属性props已更改?

至少,这似乎是我所做的测试的情况。如果父组件更改了任何道具,则会props创建一个新对象。

我将不胜感激任何证明这一点的官方文档链接。

javascript reactjs

2
推荐指数
1
解决办法
331
查看次数