【发布时间】:2021-05-22 19:24:01
【问题描述】:
我正在实现一个使用 Json 生成的表单。 Json 从 API 中检索,然后循环遍历我呈现输入元素的项目。这是示例 Json:
{
name: {
elementType: 'input',
label: 'Name',
elementConfig: {
type: 'text',
placeholder: 'Enter name'
},
value: '',
validation: {
required: true
},
valid: false,
touched: false
}
}
这是我呈现表单的方式:
render() {
const formElementsArray = [];
for (const key in this.props.deviceConfig.sensorForm) {
formElementsArray.push({
id: key,
config: this.props.deviceConfig.sensorForm[key]
});
const itemPerRow = 4;
const rows = [
...Array(Math.ceil(props.formElementsArray.length / itemPerRow))
];
const formElementRows = rows.map((row, idx) =>
props.formElementsArray.slice(
idx * itemPerRow,
idx * itemPerRow + itemPerRow
)
);
const content = formElementRows.map((row, idx) => (
<div className='row' key={idx}>
{row.map((formElement) => (
<div className='col-md-3' key={formElement.id}>
<Input
key={formElement.id}
elementType={formElement.config.elementType}
elementConfig={formElement.config.elementConfig}
value={formElement.config.value}
invalid={!formElement.config.valid}
shouldValidate={formElement.config.validation}
touched={formElement.config.touched}
label={formElement.config.label}
handleChange={(event) => props.changed(event, formElement.id)}
/>
</div>
))}
</div>
...
}
我将表单状态存储在 redux 中,并且在每次输入更改时,我都会更新状态。现在的问题是每次我更新状态时,整个表单都会再次重新渲染......有没有办法优化它,使得只有更新的表单元素被重新渲染?
编辑:
-
我在
Input.js中使用了React.memo作为:export default React.memo(input); -
我的有状态组件是纯组件。
-
Parent 是类组件。
编辑 2:
这是我创建 formElementArray 的方法:
const formElementsArray = [];
for (const key in this.props.deviceConfig.sensorForm) {
formElementsArray.push({
id: key,
config: this.props.deviceConfig.sensorForm[key]
});
【问题讨论】:
-
我在您的 json 中没有看到 id - 有吗?
-
@WillJenkins id 是 Json 中的键名,即
name -
name如何映射到id?它没有显示在您的问题中
标签: javascript reactjs optimization redux