pro-components icon indicating copy to clipboard operation
pro-components copied to clipboard

ProForm的transform不支持自动处理多层嵌套的数据👑 [需求]

Open xiaoweiSun opened this issue 2 years ago • 1 comments

提问前先看看:

https://github.com/ryanhanwu/How-To-Ask-Questions-The-Smart-Way/blob/main/README-zh_CN.md

🔩 所属模块或组件

ProForm

🥰 需求描述

如果想调用transform处理数据,但是是在比较深的层级,比如{ a: { b: { c: 'xxxx' } } },想处理c的值,在transform中需要return { a: { b: { c: 'yyyy' } } }。希望能有一个默认的逻辑,让数据维持在其原本所属的层级上

⛰ 功能需求适用场景

有时候自己封装一个公用组件,提前写好transform,但是它在form中的位置不固定,目前就无法写这个transform

🧐 解决方案

可能的解决方案:第二个参数namePath,可以是一个层级的key的数组,比如:['a', 'b', 'c'],或者新加一个参数来表示,这样就可以处理了

xiaoweiSun avatar Aug 29 '22 09:08 xiaoweiSun

onChange方法也有这个问题

xiaoweiSun avatar Sep 07 '22 12:09 xiaoweiSun

TAutomatically replying with ChatGPT can be attempted, but it cannot be guaranteed to be completely accurate and may not fully address all issues. Please feel free to reply if you have any further questions or concerns. 此回复基于 ChatGPT 自动生成,可以尝试下方案,官方员会在一定时间后继续继续处理。

如果你使用 ProForm 的 onChange 方法,并且要处理深层级数据的情况,也需要传递一个 namePath 参数,以保持所属层级。可以按照以下步骤实现:

  1. 在 onChange 方法中获取到当前的值和对应的 key,可以使用 namePath 参数来获取。例如:
const handleChange = (value, key, namePath) => {
  console.log(`namePath: ${namePath}, key: ${key}, value: ${value}`);
  // 处理数据的逻辑
}
  1. 构造一个新的 value,使其保持在原始层级上。可以使用 lodashset 方法来实现。
const { set } = require('lodash');

const handleChange = (value, key, namePath) => {
  const data = { [key]: value };
  const newData = set({}, namePath.concat(key), data);
  console.log(`newData: ${JSON.stringify(newData)}`);
  // 处理数据的逻辑
}

以上代码中,我们先用一个对象 data 保存当前的 key 和 value,然后再使用 lodashset 方法来构造出一个新的对象 newData,使其保持在原始层级上。

  1. 将处理后的数据回写到表单中。可以使用 setFieldsValue 来实现。
const { set } = require('lodash');

const handleChange = (value, key, namePath, form) => {
  const data = { [key]: value };
  const newData = set({}, namePath.concat(key), data);
  console.log(`newData: ${JSON.stringify(newData)}`);
  form.setFieldsValue(newData);
  // 处理数据的逻辑
}

以上代码中,我们将构造好的 newData 通过 setFieldsValue 方法回写到表单中。

  1. 在 ProForm 中使用 onChange 方法时,要将 namePathform 参数传递进去。
<ProForm
  initialValues={{}}
  onValuesChange={(value, values) => {}}
  submitter={{
    searchConfig: {
      submitText: '提交',
    },
  }}
>
  <ProForm.Group>
    <ProFormText name={['a', 'b', 'c']} label="输入框" />
  </ProForm.Group>
  <ProForm.Group>
    <ProFormSwitch
      name={['a', 'b', 'd']}
      label="开关"
      onChange={(value) => handleChange(value, 'd', ['a', 'b'], form)}
    />
  </ProForm.Group>
</ProForm>

以上代码中,我们在 <ProFormSwitch> 组件的 onChange 方法中调用了 handleChange 方法,并且将 namePathform 作为参数传递进去。

通过以上步骤,我们可以在 ProForm 的 onChange 方法中处理深层级数据。

chenshuai2144 avatar Mar 06 '23 10:03 chenshuai2144

+1

leshalv avatar Jun 01 '23 14:06 leshalv