[英]React hook useEffect causes initial render every time a component mounts
I am new to React hooks.我是 React 钩子的新手。 So, I wanted to implement componentWillReceiveProps with React hooks.
所以,我想用 React 钩子实现 componentWillReceiveProps。 I used React.useEffect() like so:
我像这样使用 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);
The problem is, useEffect is called each time the component renders initially, which I don't want.问题是,每次组件最初呈现时都会调用 useEffect,这是我不想要的。 I only want it to render, when "props.authLoginSuccess" changes.
我只希望它在“props.authLoginSuccess”更改时呈现。
Since you want the effect to not run on initial render, you can do that by making use of useRef
由于您希望效果不在初始渲染时运行,您可以通过使用
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]);
Wrap it in an if
condition like this:将它包装在这样的
if
条件中:
React.useEffect(() => {
if (props.authLoginSuccess) {
console.log(props.authLoginSuccess);
}
}, [props.authLoginSuccess]);
Note that the effect will still run though - both initially and every time props.authLoginSuccess
changes (which is okay!).请注意,效果仍然会运行 - 无论是最初还是每次
props.authLoginSuccess
更改时(没关系!)。
The if
block will prevent running console.log(props.authLoginSuccess)
when props.authLoginSuccess
is falsy.当
props.authLoginSuccess
为假时, if
块将阻止运行console.log(props.authLoginSuccess)
。 So if you don't want it running initially ie when component mounts , just make sure that props.authLoginSuccess
is false
initially.因此,如果您不希望它最初运行,即在组件mounts 时,只需确保
props.authLoginSuccess
最初为false
。
You could add another state that would monitor whether or not the component has been mounted.您可以添加另一个状态来监视组件是否已安装。
const [isMounted, setIsMounted] = React.useState(false);
React.useEffect(() => {
if (isMounted) {
console.log(props.authLoginSuccess);
} else {
setIsMounted(true);
}
}, [props.authLoginSuccess]);
That way, it will only execute when the component has been mounted.这样,它只会在组件被挂载后执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.