更新表单时initialValues不会更新

时间:2018-12-04 08:25:57

标签: javascript reactjs redux redux-form

我有一个名为Client的表单,该表单具有一个同时处理addedit的表单。添加有效,但是在编辑表单时 如果是,则使用initialValues填充它,并编辑表单),则不会更新initialValues。我的意思是,如果我去客户A表格并更新 字段client_name从'abc'到'xyz',则client_name将在服务器中另存为'xyz',但initialValues不会更新 因此,如果我再次进入相同的表单而不刷新页面并保存表单而不更改任何内容,那么client_name将与先前的表单一起保存 值我'abc',因为在更新字段时不会更新initialValues。

这是我的代码

import React, { Component } from 'react';
import { reduxForm, initialize } from 'redux-form';


const mapDispatchToProps = (dispatch, props) => ({
  addClient: clientData => dispatch(addClient(clientData)),
  editClient: clientData => dispatch(editClient(clientData)),
  loadClient: () => dispatch(loadClient(props.match.params.company)),
  resetClient: () => dispatch(resetClient()),
});

const mapStateToProps = createStructuredSelector({
  initialValues: selectClient(),
});


class Client extends Component<propsCheck> {
  state = {
    client: initialState,
    isLoading: false,
  };

  componentDidMount() {
    if (this.props.match.params.company) {
      this.props.loadClient();
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.match.params.company) {
      this.props.loadClient();
    } else {
      this.props.resetClient();
    }
  }

  handleChange = ({ target: { name, value } }) => {
    this.setState({ client: { ...this.state.client, [name]: value } });
  };

  handleSubmit = event => {
    event.preventDefault();
    const { client } = this.state;
    const { initialValues, addClient: add, editClient: edit } = this.props;
    if (isEmpty(initialValues)) {
      add(client);
    } else {
      const updatedClient = updatedValue(initialValues, client, 'id');
      edit(updatedClient);
    }
    this.setState({ isLoading: true });
  };

  render() {
    const { invalid, submitting, initialValues } = this.props;
    return (
          <ClientForm
            loading={this.state.isLoading}
            handleChange={this.handleChange}
            handleSubmit={this.handleSubmit}
            disabled={invalid || submitting}
            type={initialValues && initialValues.id ? 'Edit' : 'Add'}
            reset={this.props.reset}
            history={this.props.history}
          />
    );
  }
}


const withReduxForm = reduxForm({
  form: 'clientForm',
  fields: requiredFields,
  validate,
  enableReinitialize: true,
})(Client);

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

1 个答案:

答案 0 :(得分:1)

您的初始值是从redux状态(mapStateToProps中的selectClient)填充的吗?因此,当您更新/编辑client_name时,是否要在redux中更改数据?