【问题标题】:Entire form being rerendered in React with Redux state在 React 中使用 Redux 状态重新渲染整个表单
【发布时间】:2016-12-22 08:41:53
【问题描述】:

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

我已经连接了 Redux,以便将下面的 schema 和 formValues 分配为这个类的 props。因此,表单使用正确的标签、正确的输入字段类型等正确呈现。当字段上发生 onChange 事件时,应用程序状态(在 formData 下)正在正确更新。但我注意到,当应用程序状态中的 formData 发生变化时,整个表单都会重新呈现,而不仅仅是“特定字段”。这是因为我像这样将表单值存储为 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
    }));
}

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

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

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

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

    编辑:刚想到这一点,但是您是否将字段的值存储在您的状态?这感觉不对。请务必仔细阅读有关受控组件的 React 指南。 (例如,尝试使用纯 &lt;span&gt;s 而不是输入进行渲染,然后听 onKeyPress。它还能工作吗?如果不是,你可能会误用 value 属性)

    【讨论】:

    • @rom-grk- 是的,正在使用状态更新值属性。由于冗长,我没有将所有代码放在这里。我通过使用 shouldComponentUpdate() 做了上面的建议,它只更新了 props 改变的组件。
    猜你喜欢
    • 2018-01-03
    • 2020-11-15
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    相关资源
    最近更新 更多