【问题标题】:React hook useEffect causes initial render every time a component mounts每次安装组件时,React hook useEffect 都会导致初始渲染
【发布时间】:2019-12-01 20:07:06
【问题描述】:

我是 React 钩子的新手。所以,我想用 React 钩子实现 componentWillReceiveProps。 我像这样使用 React.useEffect():

React.useEffect(() => {
    console.log(props.authLoginSuccess);  // initially called every time, the component renders
  }, [props.authLoginSuccess]);


return ( //JSX...)

onst mapStateToProps = (state: any): StateProps => {
  return {
    authLoginSuccess: selectAuthLoginSuccess(state) //used selector to select authLoginSuccess
  };
};
export default connect(
  mapStateToProps,
  // mapDispatchToProps
  { authLogin, toggleLoadingStatus } 
)(Auth);


问题是,每次组件最初呈现时都会调用 useEffect,这是我不想要的。我只希望它在“props.authLoginSuccess”更改时呈现。

【问题讨论】:

  • props.authLoginSuccess是什么数据结构?
  • ...另一个疯狂的猜测:您的组件可能被其父级(或与父级一起)重新安装。您可以通过添加useEffect(() => { console.log('mounted!'); return () => console.log('unmounted');}, []) 来检查
  • @go_diego, props.authLoginSuccess 是一个布尔值。

标签: reactjs react-redux react-hooks


【解决方案1】:

由于您不希望效果在初始渲染时运行,您可以通过使用 useRef 来做到这一点

const initialRender = useRef(true);
React.useEffect(() => {
    if(initialRender.current) {
        initialRender.current = false;
    } else {
        console.log(props.authLoginSuccess);  // initially called every time, the component renders
    }
  }, [props.authLoginSuccess]);

【讨论】:

    【解决方案2】:

    您可以添加另一个状态来监控组件是否已安装。

    const [isMounted, setIsMounted] = React.useState(false);
    
    React.useEffect(() => {
      if (isMounted) {
        console.log(props.authLoginSuccess);
      } else {
        setIsMounted(true);
      }
    }, [props.authLoginSuccess]);
    

    这样,它只会在组件被挂载时执行。

    【讨论】:

    • 这是一种解决方法,我也尝试过,但对我的情况没有帮助。
    【解决方案3】:

    将其包装在if 条件中,如下所示:

    React.useEffect(() => {
      if (props.authLoginSuccess) {
        console.log(props.authLoginSuccess);
      }
    }, [props.authLoginSuccess]);
    

    请注意,效果仍然会运行 - 无论是最初还是每次props.authLoginSuccess 更改时(没关系!)。

    if 块将阻止 console.log(props.authLoginSuccess)props.authLoginSuccess 为假时运行。因此,如果您不希望它最初运行,即当组件挂载时,只需确保 props.authLoginSuccess 最初是 false

    【讨论】:

      猜你喜欢
      • 2021-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-20
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多