【问题标题】:value is not shown in the field when using redux form使用 redux 表单时字段中不显示值
【发布时间】:2018-07-03 05:51:09
【问题描述】:

我正在使用 redux-form 作为表单。表单被提交,但如果页面被刷新 我需要显示来自服务器的提交数据。一切正常, 本地状态也从 getDerivedStateFromProps 更新,但该字段没有 用数据显示。我使用了普通的输入标签,它显示了数据。我错过了什么?

这就是我所做的

更新

  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,
  // initialValues: {
  //   company_name: 'company',
  // },
  destroyOnUnmount: false,
  enableReinitialize: true,
  keepDirtyOnReinitialize: true,
});

const initialState = {
  company_name: 'hello',
  website: '',
  industry: '',
  number_of_employees: '',
  phone_number: '',
  founded: '',
  address: '',
  city: '',
  state: '',
  zip_code: '',
  country: '',
  wiki: '',
  headquarter: '',
  speciality: '',
  type: '',
};

const enhance = compose(
  withReduxForm,
  withConnect,
  withState('company', 'updateCompany', initialState),
  withHandlers({
    handleChange: props => ({ target: { name, value } }) => {
      props.updateCompany({ ...props.company, [name]: value });
    },
    handleSubmit: props => (event) => {
      event.preventDefault();
      props.saveCompany(props.company);
    },
  }),
  setStatic('getDerivedStateFromProps', (nextProps) => {
    const { company } = nextProps.getCompany;
    if (company && company.records !== undefined) {
      console.log('company records getDerivedStateFromProps', company.records);
      return {
        company: company.records,
      };
    }
    return null;
  }),
  lifecycle({
    componentDidMount() {
      this.props.loadCompany();
    },
  }),
);

export default enhance;



const Company = ({
  company,
  handleChange,
  handleSubmit,
}: {
  company: Object,
  handleChange: Function,
  handleSubmit: Function
}) => {
  console.log('company', company);
  return (
    <React.Fragment>
      <FormHeadline headline="Company" weight="400" />
      <Wrapper>
        <GridContainer container spacing={24}>
          <StyledForm autoComplete="off" onSubmit={handleSubmit}>
            <FormWrapper>
              <input
                name="company_name"
                id="company_name"
                type="text"
                label="Company Name"
                className="input-field"
                value={company.company_name}
                onChange={handleChange}
              />
              {/* <Field
                id="company_name"
                name="company_name"
                type="text"
                label="Company Name"
                className="input-field"
                value="Hello"
                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"
              />
              </FormWrapper>
            </StyledForm>
          </GridContainer>
        </Wrapper>
      </React.Fragment>
    );
  };

  export default enhance(Company);


  generic text field 

  const GTextField = ({
    input,
    label,
    meta: { touched, error },
    ...rest
  }: {
    input: any,
    label: Node,
    meta: {
      touched: boolean,
      error: boolean
    }
  }) => {
    console.log('rest', input);
    return (
      <TextField
        label={label}
        helperText={touched && error}
        error={!!(touched && error)}
        {...input}
        {...rest}
      />
    );
  };

这有效,但字段一无效

<input
  name="company_name"
  id="company_name"
  type="text"
  label="Company Name"
  className="input-field"
  value={company.company_name}
  onChange={handleChange}
/>

更新

props.initialValues 显示以下内容,但该字段仍未更新

这是完整的代码

https://gist.github.com/MilanRgm/e3e0592c72a70a4e35b72bb6107856bc

【问题讨论】:

    标签: javascript reactjs redux redux-form


    【解决方案1】:

    您好,首先将输入标签替换为注释掉的字段组件本身,然后在 reduxform 中设置这些标志

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

    以及将 initialValues 道具与服务器响应一起传递给表单容器

    {
      company_name: 'response value from server'
    }
    

    【讨论】:

    • 我不懂 initialValues 道具。请给我一个样品好吗?你的意思是使用标志initialValues?
    • 是的,你也不需要初始状态,你可以使用 initialValues 标志来设置这个
    • 我如何在 state 中使用 initialValues,因为数据必须从 initialValues 中的 reducer 中获取。
    • 你也可以将initialValues标志设置为props const mapStateToProps = state => ({ getCompany: state.profile.companyReducer, initialValues: state.profile.[your object value] });跨度>
    • 你能打印initialValues console.log(props.initialValues)的日志吗?它应该像一个对象形式{company_name: '[your value]'} 例如:你可以使用initialValues : {company_name: company && company .records}
    【解决方案2】:

    您好,请查看 fiddle link 以获取 initialValues 示例。对于您使用减速器的示例

      const mapStateToProps = state => ({ 
       getCompany: state.profile.companyReducer, 
       initialValues: state.profile.[your reducer object] });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-23
      • 2019-01-28
      • 2021-11-10
      • 1970-01-01
      相关资源
      最近更新 更多