从 processStrategy 访问父属性

Accessing parent properties from processStrategy

我有以下架构:

const dataPointSchema = new schema.Entity(
  DATA_POINT_ENTITY_TYPE,
  undefined,
  {
    processStrategy: (value, parent) => {
      console.log({parent});
      return value;
    }
  }
);
const dataPointsSchema = new schema.Array(dataPointSchema);
const dataRowSchema = new schema.Entity(
  DATA_ROW_ENTITY_TYPE,
  {_embedded: {'data-points': dataPointsSchema}}
);

const dataRowsSchema = new schema.Array(dataRowSchema);

return normalize(dataRows, dataRowsSchema);

当我 normalize 具有 data-row 的所有属性时,我希望打印出 parent,但它只显示我拥有的 data-pointsdataRowSchema 中讲述过它。这是错误还是预期的行为?

看起来正在发生的事情是 _embeddeddataPointSchema 进程策略中的父级。一个工作示例如下:

import {normalize, schema} from 'normalizr';

const someDataRows = [
{
  _embedded: {'data-points': [{id: 'Uv2k4uW_-6xzh8ImYNwh-0'}]},
  id: 'Uv2k4uW_-6xzh8ImYNwh',
  blah: 'hello'
},
{
  _embedded: {'data-points': [{id: '-B0jeFmCROeL5ICJpx-b'}]},
  id: 'D01A08',
  blah: 'hello1'
}
];

function normalizeRows(dataRows) {
  const dataPointSchema = new schema.Entity(
    'data-point',
    undefined,
    {
      processStrategy: (value, parent) => {
        console.log({parent});
        return value;
      }
    }
  );
  const dataPointsSchema = new schema.Array(dataPointSchema);
  const dataRowSchema = new schema.Entity(
    'data-row',
    {_embedded: {'data-points': dataPointsSchema}}
  );

  const dataRowsSchema = new schema.Array(dataRowSchema);

  return normalize(dataRows, dataRowsSchema);
}

normalizeRows(someDataRows);

这是正确的行为。 parent 是父对象,恰好是 _embedded 的值。从技术上讲,普通对象是一种非唯一模式。这可以在没有 shorthand 的情况下重写,因此它更有意义:

const dataRowSchema = new schema.Entity(
    'data-row',
    {_embedded: new schema.Object({'data-points': dataPointsSchema}})
);