Skip to content

Cascader 组件自定义属性名逻辑存在严重Bug #3429

@ioixioi

Description

@ioixioi

NutUI React 包名

@nutui/nutui-react-taro

NutUI React 版本号

3.0.19

平台

h5, weapp, alipay, jd, tt, 其他小程序

重现链接

重现步骤

Cascader 组件初始化步骤调用了以下归一化方法

// https://github.com/jdf2e/nutui-react/blob/feat_v3.x/src/packages/cascader/utils.ts
export const normalizeOptions = (
  options: CascaderOption[],
  keyMap: CascaderOptionKey
): CascaderOption[] | undefined => {
  if (!options) return undefined
  return options.map((opt: any) => {
    const {
      [keyMap.textKey]: text,
      [keyMap.valueKey]: value,
      [keyMap.childrenKey]: children,
      ...others
    } = opt
    return {
      text,
      value,
      children: normalizeOptions(children, keyMap),
      ...others, // 原始数据如果存在 text 或 value 属性,这里会覆盖上一步的 text 或 value 属性
    } as CascaderOption
  })
}

const ret = normalizeOptions(
  [
    { "text": "北京", "value": "021" }
  ],
  { textKey: 'text', valueKey: 'text', childrenKey: 'children' }
)
console.log(ret);
// 错误:[{ text: '北京', value: '021', children: undefined }]
// 正确:[{ text: '北京', value: '北京', children: undefined }]

期望的结果是什么?

export const normalizeOptions = (
  options: CascaderOption[],
  keyMap: CascaderOptionKey
): CascaderOption[] | undefined => {
  if (!options) return undefined
  return options.map((opt: any) => {
    const {
      [keyMap.textKey]: text,
      [keyMap.valueKey]: value,
      [keyMap.childrenKey]: children,
      ...others
    } = opt
    return {
      ...others, // 将展开运算提前,归一化的属性放后就不会被覆盖
      text,
      value,
      children: normalizeOptions(children, keyMap)
    } as CascaderOption
  })
}

const ret1 = normalizeOptions(
  [
    { "text": "北京", "value": "021" }
  ],
  { textKey: 'text', valueKey: 'text', childrenKey: 'children' }
)
console.log(ret1) // [{ text: '北京', value: '北京', children: undefined }]

const ret2 = normalizeOptions(
  [
    { "text": "北京", "value": "021" }
  ],
  { textKey: 'value', valueKey: 'value', childrenKey: 'children' }
)
console.log(ret2) // [{ text: '021', value: '021', children: undefined }]

实际的结果是什么?

当节点属性存在 text 或 value 属性时,配置了自定义节点属性后,获取不到节点的正确属性

环境信息

No response

其他补充信息

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions