什么是历史的替代品useBeforeUnload在react-router中显示确认对话框?

时间:2016-09-19 11:03:08

标签: react-router history.js

example hereissue comment中,建议使用history的useBeforeUnload函数。

然而,这个功能消失了。它似乎是removed without replacement in the current 4.x version

  

删除了"中间件" API(即所有"使用"功能)。

什么是处理这些"卸载前的好方法"案例现在是为了显示确认对话框?

1 个答案:

答案 0 :(得分:0)

看一下history的createBrowserHistory的代码,看起来block函数可以满足你的需要。来自文档:

// Register a simple prompt message that will be shown the
// user before they navigate away from the current page.
const unblock = history.block('Are you sure you want to leave this page?')

// Or use a function that returns the message when it's needed.
history.block((location, action) => {
  // The location and action arguments indicate the location
  // we're transitioning to and how we're getting there.

  // A common use case is to prevent the user from leaving the
  // page if there's a form they haven't submitted yet.
  if (input.value !== '')
    return 'Are you sure you want to leave this page?'
})

// To stop blocking transitions, call the function returned from block().
unblock()

https://github.com/mjackson/history#blocking-transitions