我有这个类可以为不同的对话加载消息:
export class Messages extends Component {
constructor() {
super();
this.state = {
page: 0,
results_per_page: 10,
messages: [],
};
this.loadAnotherSetOfMessages = this.loadAnotherSetOfMessages.bind(this);
this.checkIfUserHasPickedAnotherConversation =
this.checkIfUserHasPickedAnotherConversation.bind(this);
}
componentDidMount() {
// #NOTE
// This will load first set of messages for first conversation opened by user
this.loadAnotherSetOfMessages();
}
componentDidUpdate(prevProps, prevState) {
this.checkIfUserHasPickedAnotherConversation(prevProps);
}
loadAnotherSetOfMessages() {
const { page, results_per_page } = this.state;
const conv_id = this.props.private_chat.current_chat._id;
this.props.getXNumberOfMessages(conv_id, page, results_per_page);
this.setState({
page: this.state.page + 1,
});
}
checkIfUserHasPickedAnotherConversation(prevProps) {
const has_user_clicked_a_conversation =
!!this.props.private_chat.current_chat;
if (has_user_clicked_a_conversation) {
const previous_conv_id = prevProps.private_chat.current_chat._id;
const new_conv_id = this.props.private_chat.current_chat._id;
const has_user_picked_another_conversation =
previous_conv_id != new_conv_id;
if (has_user_picked_another_conversation) {
this.resetMessages();
this.loadAnotherSetOfMessages();
}
}
}
resetMessages() {
this.setState({
page: 0,
messages: [],
});
}
// render() {}
}
每次用户单击新对话时,我都会使用此功能重置状态resetMessages
:
if (has_user_picked_another_conversation) {
this.resetMessages();
// This function needs to get executed after the update inside resetMessages has happened
this.loadAnotherSetOfMessages();
}
这是它的定义:
resetMessages() {
this.setState({
page: 0,
messages: [],
});
}
这样当函数在它之后执行时,loadAnotherSetOfMessages
它的定义如下:
loadAnotherSetOfMessages() {
const { page, results_per_page } = this.state;
const conv_id = this.props.private_chat.current_chat._id;
this.props.getXNumberOfMessages(conv_id, page, results_per_page);
this.setState({
page: this.state.page + 1,
});
}
使用带有 value和value的初始state
参数,因为这是一个全新的对话。page
0
messages
[]
我面临的问题loadAnotherSetOfMessages
是该函数不是使用重新初始化的状态参数执行的0
,[]
而是使用先前对话的最新值执行的。
例如,如果之前的对话已经加载到页面5
,那么它将使用5
而不是0
.
我该怎么办?