reactjs - 在 componentWillUnmount 中使用 react-router 的提示
问题描述
我有一个呈现自定义表单的父组件,我在自定义表单上使用 redux 表单,我想做的是每当子组件被卸载时,如果表单上有任何值我需要提示用户是否要保存它。
所以下面是代码,提示没有发生,我正在使用状态并使用redux形式的dirty(this.props)更新状态。
所以在 componentWillUnmount 之后渲染没有发生。我错过了什么,我认为在 componentWillUnmount 之后渲染不会发生。
请看下面的代码。
**//APP.js**
import React from 'react';
class App extends Component{
state ={
data = []// array of data
}
render(){
return(
<div>
<CustomForm
data={this.state.data}
/>
</div>
)
}
}
export default App
**//CustomForm.js**
import React from 'react';
import {connect} from 'react-redux';
import CustomField from './CustomField';
import { Field, reduxForm } from 'redux-form';
import {Prompt} from 'react-router'
class CustomForm extends Component{
state ={
formChanged: false
}
onSubmit = (values) => {
console.log(values)
}
componentWillUnmount(){
if(this.props.dirty){
this.setState({
formChanged: true
})
}
}
render(){
return(
<div>
{
this.state.formChanged?
<Prompt
when={shouldBlockNavigation}
message='You have unsaved changes, are you sure you want to leave?'
/>
:
null
}
<Form onSubmit={handleSubmit(this.onSubmit)}>
<Field
name="field1"
type="text"
component={CustomField}
label="field1"
/>
</Form>
</div>
)
}
}
export default reduxForm({
form: "NewForm",
destroyOnUnmount: true,
forceUnregisterOnUnmount: false
})(connect(mapStateToProps, mapDispatchToProps)(CustomForm))
解决方案
推荐阅读
- javascript - JavaScript:读取 excel 单元格值
- python - 如何让我的机器人在 discord.py 中删除/删除角色?
- c# - 为包含存储库和工作单元的域层创建测试
- elasticsearch - [...] 上超出了高磁盘水印 [90%],分片将从该节点移出
- javascript - Vue:为什么我的 html 表格列显示为单条直线?
- sql-server - 如何根据同一表中的其他行更新列的值
- html - 我如何能够进行自动化前端测试?
- r - 如何为 Cronbach 的 Alpha & ICC (metafor) 生成森林图?
- javascript - 在Phonegap App中下载HTML/页面为PDF
- python - 如何使用for循环在字典中添加值?