React:尝试用 react hook useEffect 重写 ComponentDidUpdate(prevProps),但它在应用程序启动时触发

React: Trying to rewrite ComponentDidUpdate(prevProps) with react hook useEffect, but it fires when the app starts

我正在使用 componentDidUpdate 函数

componentDidUpdate(prevProps){
     if(prevProps.value !== this.props.users){ 
        ipcRenderer.send('userList:store',this.props.users);    
}

至此

const users = useSelector(state => state.reddit.users)

    useEffect(() => {
       console.log('users changed')
       console.log({users})
    }, [users]);

但我在启动应用程序时收到消息 'users changed'。但是用户状态根本没有改变

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

从:Using the Effect Hook

这将在您的 DOM 中绘制组件时调用,这可能更接近 componentDidMount

是的,这就是 useEffect 的工作原理。默认情况下,它在每次渲染后 运行s。如果您提供一个数组作为第二个参数,它将在第一次渲染时 运行,但如果指定的值未更改,则跳过后续渲染。没有内置方法可以跳过第一次渲染,因为这种情况非常罕见。

如果您希望代码对第一次渲染没有影响,您将需要做一些额外的工作。您可以使用 useRef 创建一个可变变量,并更改它以指示第一次渲染完成后。例如:

  const isFirstRender = useRef(true);
  const users = useSelector(state => state.reddit.users);
  useEffect(() => {
    if (isFirstRender.current) {
      isFirstRender.current = false;
    } else {
       console.log('users changed')
       console.log({users})
    }
  }, [users]);

如果您发现自己经常这样做,您可以创建一个自定义挂钩,以便更轻松地重用它。像这样:

const useUpdateEffect = (callback, dependencies) => {
  const isFirstRender = useRef(true);
  useEffect(() => {
    if (isFirstRender.current) {
      isFirstRender.current = false;
    } else {
      return callback();
    }

  }, dependencies);
}

// to be used like:

const users = useSelector(state => state.reddit.users);
useUpdateEffect(() => {
  console.log('users changed')
  console.log({users})
}, [users]);