首页 > 解决方案 > 在 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))

标签: reactjsreact-redux

解决方案


推荐阅读