当用户离开时,Redux表单状态丢失

时间:2019-04-11 17:00:17

标签: reactjs redux react-router redux-form

我有一个简单的React应用,在其中显示redux形式的下拉列表。用户从该下拉菜单中选择一个选项,并且此选项显示在“标题”组件中。

由于使用redux-form,此选项存储在redux存储中,并且可以通过formValueSelector函数(同样来自redux-form lib)进行访问。

但是,当用户定向到应用程序中的新页面时,该用户选择的选项将在redux存储中丢失。如何解决此问题?

我尝试用withRouter包装我的Header组件,但这似乎无法解决。.

这是我的主页组件,具有redux形式:

import React from 'react'
import { Field, reduxForm } from 'redux-form'
import { Link } from 'react-router-dom'

const centres = ['Ponders End', 'North Finchley', 'Hendon', 'Walthamstow']

const renderCentreDropdown = ({ input, label }) => {
  console.log({ input })
  return (
    <div className="inline field">
      <label>{label}</label>
      <select {...input} >
        <option value="">Select a centre...</option>
        {centres.map(centre => (
          <option value={centre} key={centre}>
            {centre}
          </option>
        ))}
      </select>
    </div>
  )
}

let HomePage = () => {
  return (
    <div className="ui middle aligned center aligned grid">
      <div className="column">
        <form className="ui large form">
          <div className="ui segment">
            <Field name="centreSelect" label="Select a centre: " component={renderCentreDropdown} />
            <div className="field">
              <div className="ui left icon input">
                <i className="user icon" />
                <input type="text" name="email" placeholder="E-mail address" />
              </div>
            </div>
            <div className="field">
              <div className="ui left icon input">
                <i className="lock icon" />
                <input type="password" name="password" placeholder="Password" />
              </div>
            </div>
          </div>
          <Link to="/todaysclass" className="ui fluid large pink submit button">Login</Link>
        </form>
      </div>
    </div>
  )
}

HomePage = reduxForm({
  form: 'centreSelectForm'
})(HomePage)

export default HomePage

这是我的Header组件:

import React from 'react'
import { connect } from 'react-redux'
import moment from 'moment'
import { formValueSelector } from 'redux-form'

class Header extends React.Component {

  render() {
    console.log(this.props)
    return (
      <div className="ui secondary menu" >
        <h2 className="ui dividing header">Axis Tuition Centre{(this.props.centreName) ? ` - ${this.props.centreName}` : ''} </h2>
        <div className="right menu" >
          {moment().format('Do MMMM YYYY')}
        </div>
      </div>
    )
  }
}


const selector = formValueSelector('centreSelectForm')

export default connect(state => {
  const centreName = selector(state, 'centreSelect')
  return {
    centreName
  }
})(Header)

1 个答案:

答案 0 :(得分:1)

默认情况下,当存在表单的组件处于未安装状态时,redux-form会破坏表单的状态,因此要保留表单的状态并在其他组件中或在路由后访问它,请设置destroyOnUnmount: falsereduxForm中的HomePage中。

这将为您工作:

HomePage = reduxForm({
  form: 'centreSelectForm',
  destroyOnUnmount: false
})(HomePage)