Redux Form - Не удается заставить работать пример "Initialize from state" - TypeError: Невозможно вызвать класс как функцию

У меня есть форма (избыточная форма), которая работает просто отлично. Я пытаюсь слить defaultInitialValues с картой, находящейся в состоянии редукции, я попробовал официальный пример ( https://redux-form.com/7.3.0/examples/initializefromstate/), но не могу заставить его работать.

Вот рабочий код (без получения карты из штата):

import React, { Component } from 'react';
import { getFormSyncErrors, getFormValues, reduxForm } from 'redux-form';
import compose from 'recompose/compose';
import { connect } from 'react-redux';

class SimulatorForm extends Component {
  constructor(props) {
    super(props);

    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    event.preventDefault();

    //...
  }

  render() {
    // ...
  }
}

const defaultInitialValues = {
  name: 'john doe',
};

// Bind redux-form values as props for this form.
const mapStateToProps = state => {
  return ({
    values: getFormValues('simulator')(state),
    errors: getFormSyncErrors('simulator')(state),
  });
};

export default compose(
  reduxForm({
    form: 'simulator',
    initialValues: defaultInitialValues,
  }),
  connect(mapStateToProps),
)(SimulatorForm);

Следуя примеру, я попытался сделать следующее (конец файла):

// Decorate with reduxForm(). It will read the initialValues prop provided by connect()
SimulatorForm = reduxForm({
  form: 'simulator', // a unique identifier for this form
})(SimulatorForm);

// You have to connect() to any reducers that you wish to connect to yourself
SimulatorForm = connect(
  state => ({
    initialValues: { ...defaultInitialValues, ...{ institution: 'tata' } },
  }),
  connect(mapStateToProps),
)(SimulatorForm);

export default SimulatorForm;

Но я получаю

TypeError: Невозможно вызвать класс как функцию _classCallCheck node_modules/ реагировать-редукса /es/components/connectAdvanced.js:3

Я, наверное, упускаю что-то простое, но не могу понять, что.

1 ответ

Я действительно нашел решение после написания всего вопроса и решил опубликовать вопрос / ответ вместо того, чтобы удалить его, я надеюсь, что это поможет другим людям!

const defaultInitialValues = {
  name:'john doe',
};

// Bind redux-form values as props for this form.
const mapStateToProps = state => {
  return ({
    values: getFormValues('simulator')(state),
    errors: getFormSyncErrors('simulator')(state),
  });
};

const mapDispatchToProps = dispatch => ({
  goToStep2: () => dispatch({
    type: 'GO_TO_STEP_2',
  }),
});

// XXX If your Form depends on state values (like mine does), you MUST load them BEFORE loading the form itself, or they'll be undefined and your app will likely crash 
SimulatorForm = connect(mapStateToProps, mapDispatchToProps)(SimulatorForm);

// Decorate with reduxForm(). It will read the initialValues prop provided by connect()
// XXX See https://redux-form.com/7.3.0/examples/initializefromstate/
SimulatorForm = reduxForm({
  form: 'simulator', // a unique identifier for this form
})(SimulatorForm);

// Here happens the magic, getting values from state and merging them with default values
export default connect(
  state => {
    const initialValuesFromSettings = state.simulator.settings.modules.formInitialValues.enabled === true ?
      state.simulator.settings.modules.formInitialValues.values
      : {};

    return {
      initialValues: { ...defaultInitialValues, ...initialValuesFromSettings },
    };
  },
)(SimulatorForm);
Другие вопросы по тегам