Using React, I have the following functional component where I make use of useEffect()
:
import React, { useEffect } from 'react';
import { connect } from 'react-redux';
const MessagingComponent = React.memo(({ loadMessages, messages, ...props }) => {
useEffect(() => {
loadMessages();
});
return <div {...props}>These are the messages</div>;
});
const mapDispatchToProps = dispatch => ({
loadMessages: () => dispatch({ type: 'LOAD_MESSAGES' })
});
const mapStateToProps = state => {
return {
messages: state.chatt.messages.chatMessages
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(MessagingComponent);
As you can see, I have an effect callback that calls the loadMessages()
function in the useEffect()
callback in my MessagingComponent
:
useEffect(() => {
loadMessages();
});
The call to loadMessages()
loads messages which causes the component to re-render. This behaviour is as expected, however the problem is that the re-render causes the useEffect()
hook to fire again, which causes loadMessages()
to be called again. This in turn loads the messages from the back-end and causes the component to render again, and the cycle repeats.
How can I avoid this? Should I simply put an if condition in the useEffect()
hook, and check for the messages property?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…