【问题标题】:Redux Form - initialValues not set on page loadRedux 表单 - 页面加载时未设置初始值
【发布时间】:2020-11-07 04:18:44
【问题描述】:

我在使用 redux-form 设置初始表单字段值时遇到了一些问题。

这是我试过的代码

import { Field, FieldArray, reduxForm, getFormValues, change } from 'redux-form'

const renderField = ({
  input,
  label,
  type,
  meta: { asyncValidating, touched, error }
}) => (
  <div>
    <label>{label}</label>
    <div className={asyncValidating ? 'async-validating' : ''}>
      <input {...input} type={type} placeholder={label}/>
      {touched && error && <span>{error}</span>}
    </div>
  </div>
)
class Profile extends Component {

  constructor(props) {
    super(props);
    this.state = {
      firstName: null,
      lastName: null,
    }
  }
  
  componentDidMount() {
    this.props.fetchProfile();    
  }

  async handleChange(e) {
    await this.setState({ 'initialValues': { [e.target.name] : e.target.value }});
    await this.setState({ [e.target.name] : e.target.value });
  }

onSubmit = (e) => {
    this.props.saveProfile({
      firstName: this.state.auth.firstName,
      lastName: this.state.auth.lastName,
    });
  }

  componentWillReceiveProps(nextProps) {
    this.setState({ 
      firstName : nextProps.initialValues.firstName,
      lastName : nextProps.initialValues.LastName,
     });

    this.setState({ 'initialValues': {
      firstName : nextProps.initialValues.firstName,
      lastName : nextProps.initialValues.LastName,
     }});
  }
render() {
    return (
      <>
        <form onSubmit={handleSubmit(this.onSubmit)}>
          <div>
          <Field
              name="firstName"
              type="text"
              component={renderField}
              label="firstName"
              onChange={this.handleChange.bind(this)}
            />
          </div>
          <div>
          <Field
              name="lastName"
              type="text"
              component={renderField}
              label="lastName"
              onChange={this.handleChange.bind(this)}
            />
          </div>
          <div>
            <button type="submit" disabled={pristine || submitting}>
              Update Info
            </button>
          </div>
    </form>
);
  }
}

Profile = reduxForm({
  form: 'Profile' ,
 // fields,
  validate,
  asyncValidate,
  enableReinitialize: true,
})(Profile);

function mapStateToProps(state, props){
  let firstName = '';
  let lastName = '';
  return {
    userData: state.auth.userData,
    initialValues:{
      firstName: state.auth.firstName,
      lastName: state.auth.lastName,
    }
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    fetchProfile: () => dispatch(auth.actions.fetchProfile()),
  }
} 

export default connect(mapStateToProps, mapDispatchToProps)(Profile);

但是加载时它没有在字段中设置值。字段是空的

【问题讨论】:

  • 在componentWillReceiveProps 中获取 API 响应和值是否正确更新?您是否尝试将这些值更改为 value={this.state.firstName ?? ''} 到 value={this.state.firstName || ''}?
  • @PrathapReddy:每当我更改值时,handleChange 都会调用并且键值是正确的,尽管状态没有更新
  • 这个答案最后对你有帮助吗?如果没有,请您发布您的解决方案以帮助其他有类似问题的人。谢谢。 @bhumi-shah
  • @PrathapReddy 是的答案有帮助,这就是接受的原因!您应该将 formprops 注释添加到答案中,因为它可以帮助其他人解决相同的问题
  • 我还没有收到赏金,因此我在meta 中有questioned 它来了解bounty 的过程。根据answerers cmets 在meta 问题中发布我之前的评论以了解它是否真的对您有所帮助。反正没有冒犯。只是想知道为什么我错过了bounty。感谢您的澄清。 :-)

标签: reactjs react-redux redux-form


【解决方案1】:

我猜Redux Form 的工作方式略有不同。

您无需设置显式的onChange 处理程序或声明任何状态以在Redux Form 中保存表单fields 数据。更新类似于下面的代码

import { Field, FieldArray, reduxForm, getFormValues, change } from 'redux-form'

const renderField = ({
  input,
  label,
  type,
  meta: { asyncValidating, touched, error }
}) => (
  <div>
    <label>{label}</label>
    <div className={asyncValidating ? 'async-validating' : ''}>
      <input {...input} type={type} placeholder={label}/>
      {touched && error && <span>{error}</span>}
    </div>
  </div>
)
class Profile extends Component {
  // No need constructor/to explicitly declare the state
  componentDidMount() {
    this.props.fetchProfile();    
  }

render() {
    const { handleSubmit, pristine, submitting} = props; // You can have custom handleSubmit too
    return (
      <>
        <form onSubmit={handleSubmit}>
          <div>
          <Field
              name="firstName"
              type="text"
              component={renderField}
              label="firstName"
            />
          </div>
          <div>
          <Field
              name="lastName"
              type="text"
              component={renderField}
              label="lastName"
            />
          </div>
          <div>
            <button type="submit" disabled={pristine || submitting}>
              Update Info
            </button>
          </div>
    </form>
);
  }
}

Profile = reduxForm({
  form: 'Profile' ,
 // fields,
  validate,
  asyncValidate,
  enableReinitialize: true,
})(Profile);

function mapStateToProps(state, props) {
  return {
    userData: state.auth.userData,
    initialValues:{ // These are the initial values. You can give any name here for testing to verify the ReduxForm working
      firstName: state.auth.firstName,
      lastName: state.auth.lastName,
    }
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    fetchProfile: () => dispatch(auth.actions.fetchProfile()),
  }
} 

export default connect(mapStateToProps, mapDispatchToProps)(Profile);

question 和answer 中的示例肯定会帮助您更好地理解事物。

【讨论】:

  • 这仍然是一个问题。
  • 在键入时执行handleChange 时,您是否在console 中遇到任何问题?
  • 更新了 componentWillReceiveProps 并将 handleChange 设置为异步。查看更新的代码
  • 当我点击提交时,它会得到以前的值而不是新的值
  • 无需更改handleChange async。您可以尝试进行 2 项更改吗? 1)答案中建议的构造函数绑定。 2)像这样onChange={this.handleChange}的onChange中的简单映射
猜你喜欢
  • 1970-01-01
  • 2011-03-19
  • 1970-01-01
  • 1970-01-01
  • 2020-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-25
相关资源
最近更新 更多