Introduction: The project has a requirement: jump route, before leaving the page, need to pop up the box to ask whether the user is sure to leave. Using the react-Router
Look at this: stackoverflow.com/questions/3… (1) use the react-router
import { Prompt } from 'react-router'
<Prompt
message="Are you sure you want to leave?"
/>
Copy the code
(2)
<Prompt
when={true}
message={(location) => {
return window.confirm(`confirm to leave to ${location.pathname}? `);
}}
/>
Copy the code
(3) history.block, this is a pit!
import { history } from 'path/to/history';
class MyComponent extends React.Component {
componentDidMount() {
history.block(targetLocation= > {
// take your action here
return false;
});
}
render() {
//component render here
}
}
Copy the code
The reason for the crash is that the history.block() method cannot be used side-by-side with the
component, and the
component must be called inside the history.block(), which leads to a problem: How do onOk and onCancel in the
component return values to the return statement (return false/true) of history.block(), What about not having the history.block() return statement execute sequentially with the
component?
In plain terms, the
component displays first, blocks return false/true after it, and returns false/true after the
component’s onOk and onCancel methods are executed
I tried several methods, but they didn’t work, until I found this article: Using react-Router V4 Prompt with Custom Modal Component
(4) When leaving the page, route jump, custom pop-up box interception, and ask
handlePrompt = location= > {
if (!this.isSave) {
this.showModalSave(location);
return false;
}
return true;
};
showModalSave = location= > {
this.setState({
modalVisible: true.
location,
});
};
closeModalSave = (a)= > {
const { location } = this.state;
const { history } = this.props;
this.setState({
modalVisible: false.
});
history.push({
pathname: `..${location.pathname}`.
});
};
handlePrompt = location= > {
if (!this.isSave) {
this.showModalSave(location);
return false;
}
return true;
};
handleSave = (a)= > {
const { location } = this.state;
const { history } = this.props;
this.isSave = true;
console.log(location.pathname, 'pathname75');
history.push({
pathname: `..${location.pathname}`.
});
this.setState({
modalVisible: false.
});
this.saveAll();
};
<Prompt message={this.handlePrompt}/>
<Modal title="Tip"
visible={modalVisible}
onCancel={this.closeModalSave}
closable={false}
centered
footer={null}
>
<div>Do you want to save the changes?</div>
<div>
<Button onClick={this.closeModalSave}>
Do not save
</Button>
<Button onClick={this.handleSave}>
save
</Button>
</div>
</Modal>
Copy the code
Perfect implementation off page, route interception while displaying custom modal box!
(after)