2

我正在使用 getDerivedStateFromProps 更新状态,以便在用户刷新页面时可以更新公司对象。它更新了我通过调试内部组件检查的公司对象,但是当我尝试更改字段中的值时,公司对象(props.company inside withHandler)没有更新公司对象。为什么呢?

这是代码

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

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

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)),
});

const withConnect = connect(
  mapStateToProps,
  mapDispatchToProps,
);

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

const enhance = compose(
  withConnect,
  withReduxForm,
  withState('company', 'updateCompany', initialState),
  withHandlers({
    handleChange: props => ({ target: { name, value } }) => {
      console.log('########################################');
      // here the updated company object is not shown
      console.log('props.company', props.company, name, value);
      props.updateCompany({ ...props.company, [name]: value });
    },
    handleSubmit: props => (event) => {
      event.preventDefault();
      props.saveCompany(props.company);
    },
  }),
  setStatic('getDerivedStateFromProps', (nextProps, prevState) => {
    const { company } = nextProps.getCompany;
    if (company && company.records !== undefined) {
      const { records } = company;
      return {
        company: {
          company_name: records.company_name || ' ',
          website: records.website || '',
          industry: records.industry || '',
          number_of_employees: records.number_of_employees || '',
          phone_number: records.phone_number || '',
          founded: records.founded || '',
          address: records.address || '',
          city: records.city || '',
        },
      };
    }
    return null;
  }),
  lifecycle({
    componentDidMount() {
      this.props.loadCompany();
    },
  }),
);

export default enhance;
4

0 回答 0