Redux 表单 - 页面加载时未设置初始值

Redux Form - initialValues not set on page load

我在使用 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);

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

我想 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);

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