我试图在执行之前找到一种拦截路由更改的方法来对表单执行脏检查,提示用户输入确认消息(比如,您有待更改,是否确定要丢弃?)
目前,我已尝试在onLeave prop上添加一个函数
所以我非常想找到像这样的东西
<Route onLeave={() => doSomething()} />
const doSomething = (ev) => {
if(confirm("Are you sure")){
//Continue the routing
return true;
}else{
//Dont route, stay on the current page
return false;
}
}
答案 0 :(得分:2)
在react-router 2.4.0中,路由器对象可以通过this.context
组件(docs)作为道具传递给子组件。在2.4.0之前的版本中,您必须通过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:
if (!this.state.isSaved)
return 'Your work is not saved! Are you sure you want to leave?'
}
})
)
,根据我们的经验,这一点很难处理。然后你可以在离开路线之前检查componentDidMount。
var viwBar = BarChartView()
viwBar.leftAxis.drawGridLinesEnabled = false
viwBar.rightAxis.drawGridLinesEnabled = false
viwBar.xAxis.drawGridLinesEnabled = false
viwBar.drawGridBackgroundEnabled = false
//removes left and right axis representation
let yaxis = viwBar.getAxis(ChartYAxis.AxisDependency.Left)
yaxis.drawLabelsEnabled = false
yaxis.enabled = false
let xaxis = viwBar.getAxis(ChartYAxis.AxisDependency.Right)
xaxis.drawLabelsEnabled = false
xaxis.enabled = false
(取自docs)
答案 1 :(得分:1)
使用当前react-router-dom
,我们可以使用Prompt,我使用了redux-form
从Prompt
react-router-dom
组件
import { Prompt } from 'react-router-dom'
在表单组件的render()函数中使用
<Prompt
when={this.props.dirty}
message="Your work is not saved! Are you sure you want to leave? "
/>