Normalize 在 redux 形式中只被调用一次

Normalize is called only once in redux form

我正在使用用户输入左侧的 pad 标准化器。 我的功能是这样的:

export const padLeft = (num, len) => (
  len > num.toString().length ? '0'.repeat(len - num.toString().length) + num
    : num
);

我的标准是这样的:

const normalizeCid = (value) => {
  return padLeft(value, 8);
};

当我像这样在 Field 组件中使用它时:

<Field
        id="searchCif"
        name="searchCif"
        floatingLabelText={SEARCHVIEW_HINT_CIF}
        component={InputTextField}
        disabled={(props.afm !== undefined)}
        normalize={normalizeCid}
      />

我输入了一个输入,例如 2,它显示 00000002 是正确的,但是当我输入 23 时,零并没有减少。它显示 000000023。为什么会这样?

我认为函数 normalizeCid 运行 每个值都会改变,但是第一次 运行 它并键入“2”,传递给 padLeft 的值为 2,它 returns 并显示 00000002。

然后,当你在显示值(00000002)上加上'3'时,传入padLeft的值是000000023,长度为9,大于8,所以它只是 returns 原始值。

所以问题是 padLeft 函数中的逻辑错误。

padLeft 函数似乎只要传递一个没有任何前导零的数字就可以工作,因此我们可以通过在将值传递给 padLeft:

const normalizeCid = (value) => {
  const noLeadingZeros = value.toString().replace(/\b(0+)/, '');
  return padLeft(noLeadingZeros, 8);
};
const padLeft = (num, len) => (
  // num is already a string now
  len > num.length ? '0'.repeat(len - num.toString().length) + num
    : num
);

注意:此建议可能不适用于所有边缘情况,因此您可能需要在某处添加一些额外条件。