【问题标题】:React: Trying to rewrite ComponentDidUpdate(prevProps) with react hook useEffect, but it fires when the app startsReact:尝试使用 react hook useEffect 重写 ComponentDidUpdate(prevProps),但它在应用程序启动时触发
【发布时间】:2019-07-29 15:25:24
【问题描述】:

我正在使用 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]);

但是当我启动应用程序时,我收到消息“用户已更改”。但是用户状态没有完全改变

【问题讨论】:

标签: reactjs redux react-redux react-hooks


【解决方案1】:

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

如果您需要代码对第一次渲染没有影响,您将需要做一些额外的工作。您可以使用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]);

【讨论】:

  • 谢谢。这行得通。但是当我将另一个 useEffect 用于“guest”时,它仍然会在启动时触发。有解决办法吗?
  • 如果您发现自己经常需要这样做,我建议您将代码提取到自定义挂钩中。我已经编辑了一个这样的例子。
【解决方案2】:

如果你熟悉 React 类生命周期方法,你可以想 useEffect Hook 为 componentDidMount、componentDidUpdate 和 componentWillUnmount 组合。

来自:Using the Effect Hook

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

【讨论】:

    猜你喜欢
    • 2020-01-07
    • 1970-01-01
    • 2020-11-21
    • 2021-01-02
    • 2021-08-13
    • 1970-01-01
    • 2021-11-07
    • 2022-11-23
    • 1970-01-01
    相关资源
    最近更新 更多