我有一个模式(某种自定义吐司),当showModal变量设置为true时,它会显示在以下名为Details
的类中。
class Details extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
code: null,
publication: null,
loading: false,
circleloading: false,
showModal: false
};
this.setReady = this.setReady.bind(this);
}
handleSendMessage(event, errors) {
event.preventDefault();
let currentComponent = this;
let ownerEmail = this.state.publication.userEmail;
let title = this.state.publication.title;
let emailDTO = JsonService.getJSONParsed(event.target);
emailDTO.ownerEmail = ownerEmail;
emailDTO.title = title;
if (Object.keys(errors).length === 0) {
this.setState({
loading: true,
showModal: false,
});
UserService.sendMessage(emailDTO).then(function(response) {
currentComponent.setState({
loading: false,
showModal: true, // This works fine, but it turns out the modal then gets shown after every render
});
});
}
}
render() {
return (
<div>
<ToastNotification
show={this.state.showModal}
title={t('details.messageTitle')}
information={t('details.messageDetail')}
type='Information'
checkModal={false}
specialCloseModal={false}
/>
<ImageVisualizer
publicationid={query.publicationid}
maxImages={this.state.publication.images}
isFavourite={this.state.publication.favourite}
page='Details'
imageClass='imageSize'
containerClass='img-with-tag mySlides'
nextClass='next-image-details pointer centerArrow'
previousClass='prev-image-details pointer centerArrow'
setReady={this.setReady}
index={0}
/>
</div>
);
}
}
export default withRouter(withTranslation()(Details));
在调用UserService.sendMessage之后,将showModal设置为true,这是可以的。 出现模态。
但是问题是,每当渲染被另一个函数触发或其他任何方式再次显示模态时,都会出现问题吗? 出现后如何将showModal设置为false?
答案 0 :(得分:1)
尝试使用setTimeout设置setState showModal = false
if (Object.keys(errors).length === 0) {
this.setState({
loading: true,
showModal: false,
});
UserService.sendMessage(emailDTO).then(function (response) {
currentComponent.setState({
loading: false,
showModal: true, // This works fine, but it turns out the modal then gets shown after every render
});
setTimeout(() => {
currentComponent.setState({
showModal: true,
});
}, 200);
});
}