feat: 表单支持配置 persistDataKeys 限制只持久化部分表单项

This commit is contained in:
wuduoyi 2022-09-02 15:11:53 +08:00
parent 8e92bd5c8e
commit 67d5617f01
3 changed files with 25 additions and 4 deletions

View File

@ -1215,6 +1215,12 @@ Form 支持轮询初始化接口,步骤如下:
如果想提交成功后,清空该缓存,则配置`"clearPersistDataAfterSubmit": true`
### 限制只存储某些 key
> 2.3.0 及以上版本
如果只想存储部分 key可以配置 `"persistDataKeys": ["key1", "key2"]`,这样就只有 name 为 key1 和 key2 的表单项数据会持久化
## 禁用回车提交
表单默认情况下回车就会提交,如果想阻止这个行为,可以加上 `preventEnterSubmit` 配置项。
@ -1285,6 +1291,7 @@ Form 支持轮询初始化接口,步骤如下:
| autoFocus | `boolean` | `false` | 是否自动聚焦。 |
| canAccessSuperData | `boolean` | `true` | 指定是否可以自动获取上层的数据并映射到表单项上 |
| persistData | `string` | `""` | 指定一个唯一的 key来配置当前表单是否开启本地缓存 |
| persistDataKeys | `string[]` | `""` | 指指定只有哪些 key 缓存 |
| clearPersistDataAfterSubmit | `boolean` | `true` | 指定表单提交成功后是否清除本地缓存 |
| preventEnterSubmit | `boolean` | `false` | 禁用回车提交表单 |
| trimValues | `boolean` | `false` | trim 当前表单项的每一个值 |

View File

@ -171,6 +171,11 @@ export interface FormSchemaBase {
*/
persistData?: string;
/**
* key
*/
persistDataKeys?: string[];
/**
*
*/
@ -870,7 +875,7 @@ export default class Form extends React.Component<FormProps, object> {
submit: boolean,
changePristine = false
) {
const {store, formLazyChange} = this.props;
const {store, formLazyChange, persistDataKeys} = this.props;
if (typeof name !== 'string') {
return;
}
@ -882,7 +887,7 @@ export default class Form extends React.Component<FormProps, object> {
}
if (store.persistData && store.inited) {
store.setLocalPersistData();
store.setLocalPersistData(persistDataKeys);
}
}
formItemDispatchEvent(dispatchEvent: any) {

View File

@ -1,6 +1,7 @@
import {types, getEnv, flow, isAlive, Instance} from 'mobx-state-tree';
import debounce from 'lodash/debounce';
import toPairs from 'lodash/toPairs';
import pick from 'lodash/pick';
import {ServiceStore} from './service';
import type {IFormItemStore} from './formItem';
import {Api, ApiObject, fetchOptions, Payload} from '../types';
@ -648,8 +649,16 @@ export const FormStore = ServiceStore.named('FormStore')
self.persistData = value;
}
const setLocalPersistData = () => {
localStorage.setItem(self.persistKey, JSON.stringify(self.data));
/**
*
* @param keys key
*/
const setLocalPersistData = (keys?: string[]) => {
let data = self.data;
if (keys && keys.length) {
data = pick(data, keys);
}
localStorage.setItem(self.persistKey, JSON.stringify(data));
};
function getLocalPersistData() {