不使用本地状态创建和更新表单的替代方法

时间:2018-07-06 02:03:51

标签: javascript reactjs redux redux-form

我的申请表的用例是说我将要填写一张表。填写表格后,即使刷新页面后也应保留填写的数据。不会有任何编辑按钮。填充的数据将始终显示在其相应的字段中。为此,我按照以下方式进行了操作。我不确定这是否是一个好方法,我需要建议可以改善的地方

这就是我所做的

这是父组件

我在这里所做的是,有一个初始状态,当用户填充handleChange事件中的值时,该状态将被更新,然后将该公司对象传递给服务器。现在,当用户刷新页面时,componentDidMount会触发loadCompany函数,该函数从服务器获取该公司对象,然后保存在我在getDerivedStateFromProps中签入的getCompany缩减程序中。如果有数据,则更新本地状态,因为在Company组件中传递了值。

const initialState = {
  company_name: '',
  website: '',
  industry: '',
  number_of_employees: '',
  phone_number: '',
  founded: '',
  address: '',
  city: '',
};

const mapStateToProps = (state) => {
  const { company } = state.profile.companyReducer;
  return {
    getCompany: state.profile.companyReducer,
    initialValues: company && company.records,
  };
};

const mapDispatchToProps = dispatch => ({
  loadCompany: () => dispatch(loadCompany()),
  saveCompany: companyData => dispatch(saveCompany(companyData)),
});

class ParentCompany extends React.Component<{
  saveCompany: Function,
  loadCompany: Function,
  getCompany: Object,
  reset: Function,
}> {
  state = {
    company: initialState,
    isUpdating: true,
  };

  componentDidMount() {
    this.props.loadCompany();
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    const { company } = nextProps.getCompany;
    if (company && company.records !== undefined && prevState.isUpdating) {
      const { records } = company;
      return {
        company: records,
        isUpdating: false,
      };
    }
    return null;
  }

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

  handleSubmit = (event) => {
    event.preventDefault();
    this.props.saveCompany(this.state.company);
  };

  render() {
    const { getCompany } = this.props;
    return (
      <div>
        <Company
          success={getCompany.success}
          company={this.state.company}
          handleChange={this.handleChange}
          handleSubmit={this.handleSubmit}
          reset={this.props.reset}
        />
      </div>
    );
  }
}

const requiredFields = {
  company_name: 'Company Name',
  website: 'Website',
};

const withReduxForm = reduxForm({
  form: 'companyForm',
  fields: requiredFields,
  validate,
  destroyOnUnmount: false,
  enableReinitialize: true,
})(ParentCompany);

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

这是公司组成部分

const Company = ({
  company,
  success,
  handleChange,
  handleSubmit,
  reset,
}: {
  company: Object,
  success: Object,
  handleChange: Function,
  handleSubmit: Function,
  reset: Function
}) => (
  <React.Fragment>
    <FormHeadline headline="Company" weight="400" />
    <Wrapper>
      <Toaster />
      <GridContainer container spacing={24}>
        <StyledForm autoComplete="off" onSubmit={handleSubmit}>
          <FormWrapper>
            <Field
              id="company_name"
              name="company_name"
              type="text"
              label="Company Name"
              className="input-field"
              value={company.company_name}
              onChange={handleChange}
              component={GTextField}
              required
              margin="normal"
            />
            <Field
              id="website"
              name="website"
              type="text"
              label="Website"
              placeholder="Website"
              className="input-field"
              value={company.website}
              onChange={handleChange}
              component={GTextField}
              required
              margin="normal"
            />
            <ButtonGrid>
              <LoadingButton
                variant="raised"
                marginRight
                radius="2px"
                success={success && success}
              />
              <TransparentButton
                variant="raised"
                radius="2px"
                type="button"
                onClick={reset}
              >
                Cancel
              </TransparentButton>
            </ButtonGrid>
          </FormWrapper>
        </StyledForm>
      </GridContainer>
    </Wrapper>
  </React.Fragment>

我的目的是从专家社区了解以更好的方式完成相同工作的其他方式。

0 个答案:

没有答案