页面保存提醒
解决方案:
1.当页面不切换,仅刷新时,页面效果如图
实现原理:窗口关闭事件-beforeunload,在组件挂载时监听事件,组件卸载时移除事件监听
代码实现:
Editor = () => {
const listener = ev => {
ev.preventDefault();
ev.returnValue='are you sure?';
};
window.addEventListener('beforeunload', listener);
return () => {
window.removeEventListener('beforeunload', listener)
}
}
componentDidMount() {
this.Editor()
}
componentWillUnmount() {
this.Editor()
}
2.当页面切换时,页面效果如图
实现原理:路由守卫<Prompt/>--使用<Prompt/>,路由跳转必须通过<Link/>实现,而不能依靠<a/>原生标签。点击取消时就会留在当前页面
代码实现:
import {Button,Modal} from 'antd';
import { Prompt } from 'react-router'
class Email extends React.Component {
showModalSave = location => {
this.setState({
modalVisible: true,
location,
});
};
closeModalSave = () => {
const { location } = this.state;
const { history } = this.props;
this.isSave = false;
history.push({
pathname: `..${location.pathname}`,
});
this.setState({
modalVisible: false,
});
};
handlePrompt = location => {
if (!this.isSave) {
this.showModalSave(location);
return false;
}
return true;
};
handleSave = () => {
const { location } = this.state;
const { history } = this.props;
this.isSave = true;
history.push({
pathname: `..${location.pathname}`,
});
this.setState({
modalVisible: false,
});
// this.saveAll();
};
return (
<Prompt message={this.handlePrompt}/>
<Modal
// title="提示"
visible={this.state.modalVisible}
onCancel={this.closeModalSave}
// closable={false}
centered
width={400}
footer={null}>
<div style={{fontColor:'#1F1F1F',textAlign: 'center',height: 100,lineHeight:'100px', padding: 0 }}>Save the current Settings?</div>
<div style={{display: 'flex', padding: '0 26px' }}>
<Button style={{marginRight:60}} block size='large' type='ghost' onClick={this.closeModalSave}>Discard</Button>
<Button block size='large' type='primary' onClick={this.handleSave}>Save</Button>
</div>
</Modal>
)
}
export default Email;