【问题标题】:How to access pristine prop of reduxForm from inside the Redux state?如何从 Redux 状态内部访问 reduxForm 的原始属性?
【发布时间】:2018-08-02 13:34:59
【问题描述】:

我在我的表单中使用了多个 redux-form 的 Field 实例,并将 redux-form-material-ui 的 TextField 作为可渲染组件:

<Field
     component={TextField}
     floatingLabelText='Title:'
     name='title'
/>

当表单所在的组件被 reduxForm() 包裹时,我们会在该组件中得到props.pristineprops.dirty 等。

但是,我想根据pristine 的值,在另一个非reduxForm 组件或Redux 状态下执行一些操作,但我无法这样做。

我尝试将它作为道具传递给 Field:

<Field
    component={TextField}
    floatingLabelText='Title:'
    name='title'
    pristine={props.pristine}
/>

但是pristine 属性仍然既不是作为state.form.formName 内部的道具出现,也不是作为道具出现 里面state.form.formName.registeredFields.title

问题:
有没有办法在另一个组件或 redux 状态中获取我的表单的 pristine 属性?

【问题讨论】:

    标签: reactjs redux material-ui redux-form


    【解决方案1】:

    更新:升级到 7.4.2。解决问题!

    import { connect } from 'react-redux';
    import { isPristine } from 'redux-form'
    

    你需要做的:连接到redux-form-state并访问它

    const mapStateToProps = state => ({
      isPristine: isPristine('yourFormName')(state), // Checks whole form
      isPristine: isPristine('yourFormName')(state, ["fieldName"]), // Checks particular field
    }); connect(mapStateToProps)
    

    您可以使用 this.props.isDirty 访问它并将其传递给所需的组件。

    【讨论】:

      【解决方案2】:

      从中间件处理这个可能是检查表单之间状态、检查 form.config.values 和 form.config.initialValues 的最简单实现,当有 redux-form 更改时。

      const formMiddleware = () => store => next => action => {
        const state = store.getState()
        switch(action.type) {
          case '@@redux-form/CHANGE':
            store.dispatch({ type: UPDATE_OTHER_FORM, message: Object.is(state.form.config.values, state.form.config.initial) });
            break;
        }
        next(action)
      }
      

      另一种选择(基于用例)是通过原始状态处理您的表单,并根据道具的状态更改调用,并将其传递:

      <Button
        btnName={pristine ? "Action1" : "Action2"}
        type="submit"
        action={props.handleSubmit(values => {
          onSubmit(
            pristine ?
            {
              ...values,
              call: 'action1'
            } : {
              ...values,
              call: 'action2'
            }
          )
        })}
      />
      

      然后在您的根组件中,您可以将一个方法(在本例中为“handleSubmit”)传递给表单的 handleSubmit 属性,然后它将监视传入的表单提交,以根据值决定调用什么操作。例如

      handleSubmit = (values) => {
        if(values.call === 'action1') { 
          this.props.actions.action1(values);
        } else if(values.call === 'action2') {
          this.props.actions.action2(values);
        }
      }
      

      希望对您的特定实施有所帮助,即使您正在寻找将原始状态带出表单的方法。您也可以通过这些将状态链接到其他表单,但是当我去年研究这个时,根本不可能将状态推到表单之外。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-12
        • 2023-03-23
        • 1970-01-01
        • 2018-05-26
        • 1970-01-01
        • 1970-01-01
        • 2020-01-26
        • 1970-01-01
        相关资源
        最近更新 更多