In reagieren-Router v2.4.0
Eine der withRouter
höherer Ordnung Komponente verwenden sollten oder höher und vor v4
gibt es mehrere Optionen
- Add function
onLeave
for Route
<Route
path="/home"
onEnter={ auth }
onLeave={ showConfirm }
component={ Home }
>
- Use function
setRouteLeaveHook
for componentDidMount
Sie einen Übergang verhindern kann, geschieht oder den Benutzer auffordern, bevor eine Route verlassen mit einem Haken verlassen.
const Home = withRouter(
React.createClass({
componentDidMount() {
this.props.router.setRouteLeaveHook(this.props.route, this.routerWillLeave)
},
routerWillLeave(nextLocation) {
// return false to prevent a transition w/o prompting the user,
// or return a string to allow the user to decide:
// return `null` or nothing to let other hooks to be executed
//
// NOTE: if you return true, other hooks will not be executed!
if (!this.state.isSaved)
return 'Your work is not saved! Are you sure you want to leave?'
},
// ...
})
)
Beachten Sie, dass dieses Beispiel der Verwendung der in v2.4.0.
eingeführt withRouter
höhere Ordnung Komponente macht
Allerdings hat diese Lösung ganz perfekt funktioniert nicht, wenn die Strecke in URL zu ändern manuell
Im Sinne dass
- sehen wir die Bestätigung - ok
- enthalten der Seite nicht neu geladen - ok
- URL nicht ändert - nicht in Ordnung
jedoch in react-router v4
, sein eher einfacher mit Hilfe von Prompt
from'react-Router zu implementieren
gemäß der Dokumentation
Prompt
Used to prompt the user before navigating away from a page. When your application enters a state that should prevent the user from navigating away (like a form is half-filled out), render a <Prompt>
.
import { Prompt } from 'react-router'
<Prompt
when={formIsHalfFilledOut}
message="Are you sure you want to leave?"
/>
message: string
The message to prompt the user with when they try to navigate away.
<Prompt message="Are you sure you want to leave?"/>
message: func
Will be called with the next location and action the user is attempting to navigate to. Return a string to show a prompt to the user or true to allow the transition.
<Prompt message={location => (
`Are you sure you want to go to ${location.pathname}?`
)}/>
when: bool
Instead of conditionally rendering a <Prompt>
behind a guard, you can always render it but pass when={true}
or when={false}
to prevent or allow navigation accordingly.
in Ihrem render-Methode Sie einfach diese hinzufügen müssen, wie in der Dokumentation erwähnt Ihre nee nach d.
ich nicht jetzt, wenn dies ist, was Sie suchen, aber man kann etw tun. wie diese 'componentWillUnmount() { if (confirm ('Änderungen sind gespeichert, aber noch nicht veröffentlicht. Tun Sie das jetzt?')) { // Veröffentlichen und von einer bestimmten Seite } else { // nichts tun und gehen weg von einer bestimmten Seite } } 'so können Sie Ihren Anruf veröffentlichen Funktion Bevor verlassen der Seite – BlackSalt