每次安装组件时,React hook useEffect 都会导致初始渲染

IT技术 reactjs react-redux react-hooks
2021-05-03 11:34:47

我是 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”更改时呈现。

3个回答

由于您希望效果不在初始渲染上运行,您可以通过使用 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]);

将它包装成这样的if状态:

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

请注意,效果仍然会运行 - 最初和每次都props.authLoginSuccess发生变化(没关系!)。

if块将console.log(props.authLoginSuccess)props.authLoginSuccess为假阻止运行因此,如果您不希望它最初运行,即在组件安装时运行,只需确保它props.authLoginSuccessfalse最初的。

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

const [isMounted, setIsMounted] = React.useState(false);

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

这样,它只会在组件安装后执行。