2016-08-23 67 views
0

目前我正在使用ReactJS构建Web应用程序。该应用程序有一个注册表单。使用setRouteLeaveHook获取错误(withRouter)

现在考虑,用户已经开始注册过程。但在提交表单用户离开此注册页面之前。在这一点上,表单包含未保存的数据,我想显示一条确认消息,说明保存您在离开此屏幕前所做的更改

下面是我的代码来实现这一

componentDidMount() { 
    this.props.router.setRouteLeaveHook('/enterprise/enterprise-area/enterprise-details', 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 (true) { 
     return 'Your work is not saved! Are you sure you want to leave?'; 
    } 
    } 

export default withRouter(connect(
    mapStateToProps,{ 
    initializeVendorDetails 
})(VendorRegistration)); 

我得到如下所示的错误:

Uncaught TypeError: Cannot assign to read only property '__id__' of /enterprise/enterprise-area/enterprise-details 

我通过官方文件和github上的问题去,但一无所获。感谢预期。

+2

,我猜你的组件是不与“”直接相连,如“” 如果是这样,则必须通过this.props.rout呃从Route组件到YourComponent。 –

回答

3

@NobuhitoKurose谢谢你的回复。最后,我设法找出这里的问题。

是的,我的组件没有直接连接到路由。

我通过withRouter DOC去哪里我发现我实际上需要提供一个路由对象(this.props.route)作为第一参数,而不是作为一个字符串路线(如我在上面的代码中提到的)。

由于我的组件没有直接连接到路由我得到this.props.route未定义。

我检查了父组件(它连接到路由),并且此组件具有其路由支持。所以我只是从父组件传递这个路由道具到这个当前组件(我使用路由器),并且一切都运行良好。

下面是我的一个更新的代码

在父组件(连接到路由)

<VendorRegistration route={this.props.route}/> 

组件我使用withRouter

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: 
    // FIXME: update condition as per requirement 
    if (true) { 
    return 'You have unsaved information, are you sure you want to leave this page?'; 
    } 
} 

export default withRouter(connect(
    mapStateToProps,{ 
    initializeVendorDetails 
})(VendorRegistration)); 
+0

当您有父母 - 子女结构时,此功能可用。但是如果与父母的组件距离是多少?如果组件的学位在一种情况下是1,而在其他情况下是5呢?在这种情况下你会怎么做?泡沫路线一路?我也有这个问题。我解决这个问题的方法是查看位于“路由器”下的最后一个“路由”属性。这是我可以对我当前路线的方式:this.props.router.setRouteLeaveHook(_。last(this.props.router.routes),this.routerWillLeave); – Yaniv