zent
Version:
一套前端设计语言和基于React的实现
103 lines (89 loc) • 2.03 kB
Markdown
---
order: 23
zh-CN:
title: 批处理优化重绘性能
batchUpdate: 批量更新
update: 逐个更新
renderCount: 重绘次数
en-US:
title: Batched updates
batchUpdate: Batch Update
update: Update One by One
renderCount: Number of renders
---
```jsx
import {
Form,
Button,
FormInputField,
useObservableBatchedEagerState,
} from 'zent';
const { useState, useCallback } = React;
const formModel = Form.form({
list: Form.array(
Form.set({
v: Form.field(0),
})
).defaultValue([{ v: 1 }, { v: 2 }, { v: 3 }]),
});
function App() {
const form = Form.useForm(formModel);
return (
<Form form={form} layout="horizontal">
<List />
</Form>
);
}
function List() {
const model = Form.useFieldArray('list');
const [batchedListValue, runInBatchContext] = useObservableBatchedEagerState(
model.value$
);
console.log('list value change', batchedListValue);
const batchUpdate = useCallback(() => {
setTimeout(() => {
runInBatchContext(() => {
return new Promise(resolve => {
model.children.forEach(m => {
const vm = m.get('v');
vm.value = vm.value + 1;
});
resolve();
});
});
}, 0);
}, [model, runInBatchContext]);
const update = useCallback(() => {
setTimeout(() => {
model.children.forEach(m => {
const vm = m.get('v');
vm.value = vm.value + 1;
});
}, 0);
}, [model]);
return (
<>
{model.children.map((child, index) => {
return (
<div key={child.id}>
<FormInputField model={child.get('v')} />
</div>
);
})}
<Button onClick={batchUpdate}>{i18n.batchUpdate}</Button>
<Button onClick={update}>{i18n.update}</Button>
</>
);
}
function Preview({ form }) {
// You will see a warning about performance issues in console.
// Only do this if you know what you are doing.
const valid = useFormValid(form);
return (
<Alert type={valid ? 'success' : 'error'} style={{ marginBottom: 24 }}>
Form is {valid ? 'valid' : 'invalid'}
</Alert>
);
}
ReactDOM.render(<App />, mountNode);
```