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

React hook useEffect causes initial render every time a component mounts

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

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

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

请注意,尽管最初和每次 props.authLoginSuccess 更改时效果仍然 运行(没关系!)。

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

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

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

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

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

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