3 回答

TA貢獻1829條經驗 獲得超7個贊
react-routerv4引入了一種使用阻止導航的新方法Prompt。只需將其添加到您要阻止的組件中即可:
import { Prompt } from 'react-router'
const MyComponent = () => (
<React.Fragment>
<Prompt
when={shouldBlockNavigation}
message='You have unsaved changes, are you sure you want to leave?'
/>
{/* Component JSX */}
</React.Fragment>
)
這將阻止所有路由,但不會阻止頁面刷新或關閉。要阻止它,您需要添加以下內容(根據需要使用相應的React生命周期進行更新):
componentDidUpdate = () => {
if (shouldBlockNavigation) {
window.onbeforeunload = () => true
} else {
window.onbeforeunload = undefined
}
}
onbeforeunload具有瀏覽器的各種支持。

TA貢獻1818條經驗 獲得超8個贊
對于react-router2.4.0+
注意:建議將所有代碼遷移到最新版本,react-router以獲取所有新功能。
按照react-router文檔中的建議:
一個應該使用withRouter更高階的組件:
我們認為,這種新的HoC更好,更輕松,并且將在文檔和示例中使用它,但這并不是轉換的硬性要求。
作為文檔中的ES6示例:
import React from 'react'
import { withRouter } from 'react-router'
const Page = React.createClass({
componentDidMount() {
this.props.router.setRouteLeaveHook(this.props.route, () => {
if (this.state.unsaved)
return 'You have unsaved information, are you sure you want to leave this page?'
})
}
render() {
return <div>Stuff</div>
}
})
export default withRouter(Page)
添加回答
舉報