在 React 中使用 Redux 状态重新呈现整个表单

Entire form being rerendered in React with Redux state

我有动态 JSON 数据,并且有一个自定义方法可以通过 JSON 在页面上动态呈现表单。 JSON 架构的原因是构建各种未预定义的表单。

我已经连接了 Redux,以便下面的模式和 formValues 被指定为这个 class 的道具。因此,表单使用正确的标签、正确的输入字段类型等正确呈现。当字段上发生 onChange 事件时,应用程序状态(在 formData 下)被正确更新。但我注意到,当应用程序状态中的 formData 发生变化时,整个表单都会重新呈现,而不仅仅是 "specific fields"。这是因为我像这样将表单值存储为 formData 下的对象吗?我该如何避免这个问题?

formData = {
   userName: 'username',
   firstName: 'firstName
}

示例架构

const form =  {
  "fields":[
            {
               "label":"Username",
               "field_type":"text",
               "name":"username"
            },
            {
               "label":"First Name",
               "field_type":"text",
               "name":"firstName"
            }
    ]
  }

Redux 状态

const reducer = combineReducers({
   formSchema: FormSchema,
   formData: Form
});

//渲染方法

render() {
      const { fields } = this.props.form,
      forms = fields.map(({label, name, field_type, required }) => {
      const value = value; //assume this finds the correct value from the "formData" state.
      return (
        <div key={name}>
          <label>{label}</label>
          <input type={field_type}
            onChange={this.onChange}
            value={value}
            name={name} />
        </div>
      );
    })
}

//onchange 方法(用于受控表单输入,更新 formData 应用状态中的字段)

onChange(event) {
   this.props.dispatch(updateFormData({
      field: event.target.name,
      value: event.target.value
    }));
}

从你的示例中我不确定,但如果你在单个 render() 方法中渲染整个东西,是的,组件将再次渲染。这就是问题所在,组件。如果您尝试拥有多个组件,则应尽可能将它们分开。否则,如果状态发生变化,它会触发唯一存在的组件的重新渲染。 尽量打破它。

提示:(不知道它们是否适用但也许)

  • 使用 ref={}s
  • 实施shouldComponentUpdate()

编辑:刚想到这个,但是您是否将字段的值存储在您的状态中?这感觉不对。请务必仔细阅读有关受控组件的 React 指南。 (例如,尝试使用纯 <span>s 而不是输入进行渲染,并听取 onKeyPress。它仍然有效吗?如果不是,您可能会滥用 value 属性)