我正在尝试获取在 normalizr 模式上定义的所有键的列表,并编写了一个函数来满足我对简单模式的需求:
export const collectAttributes = target => {
const schemaKeys = []
if (target.hasOwnProperty('_key')) {
schemaKeys.push(target._key)
}
const definitions = Object.keys(target).filter(key => key[0] !== '_')
definitions.forEach(key => {
collectAttributes(target[key]).forEach(attribute => schemaKeys.push(attribute))
})
return schemaKeys
}
但是,这在嵌套模式定义上失败并出现Maximum call stack size exceeded
错误,如以下测试用例所示:
describe('collectAttributes', () => {
it('should collect all unique collections defined on a recursive schema', () => {
const nodeSchema = new schema.Entity('nodes', {})
const nodeListSchema = new schema.Array(nodeSchema)
nodeSchema.define({ children: nodeListSchema })
expect(collectAttributes(nodeSchema)).toEqual(['nodes'])
})
})
如果有人对如何收集已经访问过的模式以使递归函数停止有想法,他们将不胜感激。