该功能仅在服务器重启时有效

时间:2018-08-31 12:30:26

标签: javascript node.js

我有一个在运行节点服务器时可以运行的功能。再次刷新页面时,将引发错误。重新启动节点服务器并第三次刷新页面时,该功能将再次运行。

我有很多人

const members = [{
    imgUrl: 'resources/members/foobar.png',
    name: 'Foo Bar',
    focus: [0, 1, 2, 4, 5]
}, {
    imgUrl: 'resources/members/barfoo.png',
    name: 'Bar Foo',
    focus: [0, 1, 2, 4, 5]
}, {
    imgUrl: 'resources/members/johndoe.png',
    name: 'John Doe',
    focus: [1, 3, 5]
}];

我想修改此数组

const targetMembers = members.map(member => {
    member.focus = member.focus.map(skillIndex => skills[skillIndex]).join(', ');
    return member;
});

我得到的错误是

TypeError: member.focus.map is not a function
    at members.map.member (C:\Users\...\...\server\routes\main.js:6:37)
    at Array.map (<anonymous>)
    at router.get (C:\Users\...\...\server\routes\main.js:5:35)
    at Layer.handle [as handle_request] (C:\Users\...\...\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\...\...\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\...\...\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\...\...\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\...\...\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\...\...\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\...\...\node_modules\express\lib\router\index.js:275:10)

,我不知道为什么这只能在服务器重新加载时起作用。我在这里提供一个小片段

const members = [{
  imgUrl: 'resources/members/foobar.png',
  name: 'Foo Bar',
  focus: [0, 1, 2, 4, 5]
}, {
  imgUrl: 'resources/members/barfoo.png',
  name: 'Bar Foo',
  focus: [0, 1, 2, 4, 5]
}, {
  imgUrl: 'resources/members/johndoe.png',
  name: 'John Doe',
  focus: [1, 3, 5]
}];

const skills = [
  'Skill 0',
  'Skill 1',
  'Skill 2',
  'Skill 3',
  'Skill 4',
  'Skill 5'
];

const targetMembers = members.map(member => {
  member.focus = member.focus.map(skillIndex => skills[skillIndex]).join(', ');
  return member;
});

console.log(targetMembers);

我将每个成员的技能存储到另一个数组中,并希望在渲染模板时通过技能键(索引)来映射他们的技能。

2 个答案:

答案 0 :(得分:3)

问题出在语句上

member.focus = member.focus.map(skillIndex => skills[skillIndex]).join(', ');

首次执行-member.focusarray,数组具有函数map并执行。但是,执行后,您已将 member.focus更改为字符串

第二次执行-member.focusString,并且String没有函数映射,因此没有错误。

答案 1 :(得分:3)

这很可能是更改实际属性本身而不是映射到新属性的副作用。如果members被保留在内存中,并以某种方式尝试再次运行它,则focus现在是一个字符串,其中不包含map方法。

映射到一个新对象,而不是对现有对象进行突变:

const targetMembers = members.map(member => {
    return {
        ...member,
        focusString: member.focus.map(skillIndex => skills[skillIndex]).join(', ')
   } 
});