[英]ReactJs: How to execute a function that depends on the result of a setState that's called inside componentDidUpdate
我有这个 class 可以为不同的对话加载消息:
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() {}
}
每次用户单击新对话时,我都会使用此 function resetMessages 重置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: [],
});
}
这样当 function 之后执行时, 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,
});
}
使用值为0
的初始state
参数page
和值为[]
的messages
,因为这是一个全新的对话。
我面临的问题是 function loadAnotherSetOfMessages
不是使用重新初始化的 state 参数0
和[]
而是使用上一个对话的最新值执行的。
例如,如果之前的对话已经加载到第5
页,那么它将使用5
而不是0
。
我应该怎么办?
您不能使用 state,原因是 react 的setState
是异步的,这意味着在 state 中设置新值后,您将不得不等待组件的下一次重新渲染以获取更新的 Z9ED39E2EA93145EF573EZ 值。 如果您在设置后立即尝试获取 state 值,您将始终以之前的值结束。
所以最好的办法是,你将新的 state 值是 arguments 传递给你的loadAnotherSetOfMessages
函数并使用它。 喜欢
loadAnotherSetOfMessages(page, results_per_pag) {
const conv_id = this.props.private_chat.current_chat._id;
this.props.getXNumberOfMessages(conv_id, page, results_per_page);
this.setState({
page: page + 1,
});
}
并称它为
this.loadAnotherSetOfMessages(page, results)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.