alibaba/formily

[Bug Report] field.insert 插入(非第一项和最后一项)内容后,path 内索引下标变成字符串

fanfanyir opened this issue · 2 comments

  • I have searched the issues of this repository and believe that this is not a duplicate.

Reproduction link

Edit on CodeSandbox

Steps to reproduce

  1. 点击 add 添加一项内容
  2. 点击 copy 第一行两次
    输出值
    // 0 : ['array']
    // 1: (2) ['array', 0]
    // 2: (2) ['array', '2']
    // 3: (2) ['array', 1]

What is expected?

// 0 : ['array']
// 1: (2) ['array', 0]
// 2: (2) ['array', 1]
// 3: (2) ['array', 2]

What is actually happening?

// 0 : ['array']
// 1: (2) ['array', 0]
// 2: (2) ['array', '2']
// 3: (2) ['array', 1]

Package

@formily/react@2.3.1


这个问题发生在 ArrayField 往数组中间insert的时候,向数组尾部添加不会触发该问题。

该 issue 中的 case 在 ArrayField 执行 spliceArrayState 方法的时候,分别发生以下情况:

  • 第一次 copy, 尾部插入,元素不需要 move,插入的 field 对应 address 由 Form.createField() 生成。此时Path 对象由 FormPath.parse('array').concat(1)生成,因此segment的值为 ['array', 1]
  • 第二次 copy, 中间插入,触发 moveIndex 方法生成 fieldPatch。fieldPatch 使用 identifier 作为 address ,identifier为字符串 "array.2",丢失了数组下标的类型,因此 segment 的值为['array', '2']

const moveIndex = (identifier: string) => {
if (offset === 0) return identifier
const preStr = identifier.substring(0, addrLength)
const afterStr = identifier.substring(addrLength)
const number = afterStr.match(NumberIndexReg)?.[1]
if (number === undefined) return identifier
const index = Number(number) + offset
return `${preStr}${afterStr.replace(/^\.\d+/, `.${index}`)}`
}

@janryWang 我尝试将 moveIndex 的返回改成 FormPath.parse(preStr).concat(index) , 但是会破坏 interface INodePatch 的声明,INodePath 中的address 都是字符串类型,白总看看这个能改成Pattern 类型吗,或者还是考虑别的解决办法?