每次安装组件时,React hook useEffect 都会导致初始渲染 [英] React hook useEffect causes initial render every time a component mounts

查看:41
本文介绍了每次安装组件时,React hook useEffect 都会导致初始渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to React hooks. So, I wanted to implement componentWillReceiveProps with React hooks. I used React.useEffect() like so:

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"更改时呈现.

The problem is, useEffect is called each time the component renders initially, which I don't want. I only want it to render, when "props.authLoginSuccess" changes.

推荐答案

由于您希望效果不在初始渲染时运行,您可以使用 useRef

Since you want the effect to not run on initial render, you can do that by making use of 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]);

这篇关于每次安装组件时,React hook useEffect 都会导致初始渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆