2

我总是收到这样的错误:

未捕获(承诺中)TypeError:无法读取未定义的属性“periodListSchema”

这是我的代码:

我的架构

import { schema, arrayOf } from 'normalizr';

export const periodSchema = new schema.Entity('activePeriod');
export const periodListSchema = new schema.Array(periodSchema);

我的规范化操作

then(response => {
            console.log('normalized response', normalize(response.schema.periodListSchema));

这是我的回应

{"activePeriod":[{"periodID":2,"periodName":"Periode 27","startDate":"2016-11-11","endDate":"2016-12-11","remark":"Periode Alpha 27","isActive":"1"}],"status":"OK"}

我的 Normalzr 库是 v3.2.2 有人可以帮我找出问题所在吗?我正在努力理解这一点。

4

1 回答 1

3

1)Uncaught (in promise) TypeError: Cannot read property 'periodListSchema' of undefined抛出此错误是因为response没有schema属性,因此您无法从中获取periodListSchema属性undefined

2)要规范化响应,您应该将句点数组传递给normalizefunc,并指定schema. 此外,如果您有 id 属性的非标准名称,那么您应该在schema.Entity构造函数的选项中指定名称,通过idAttribute.

演示 webpackbin

例子

import { schema, normalize } from 'normalizr';

export const periodSchema = new schema.Entity(
  'activePeriods',
  {},
  { idAttribute:'periodID' }
);
export const periodListSchema = [periodSchema];

const response = {"activePeriod":[{"periodID":2,"periodName":"Periode 27","startDate":"2016-11-11","endDate":"2016-12-11","remark":"Periode Alpha 27","isActive":"1"}],"status":"OK"};

console.log(
  normalize(response.activePeriod, periodListSchema)
);

结果

{
  "entities": {
    "activePeriods": {
      "2": {
        "periodID": 2,
        "periodName": "Periode 27",
        "startDate": "2016-11-11",
        "endDate": "2016-12-11",
        "remark": "Periode Alpha 27",
        "isActive": "1"
      }
    }
  },
  "result": [
    2
  ]
}
于 2017-04-09T13:58:57.843 回答