我真的没有看到这出错的地方。我看过来自O'Reilly的学习反应的这个特例的帖子,由Banks&Porcello撰写。但是,这些帖子似乎工作正常,但我的例子没有。如果我有拼写错误,我看不到它。哪里是我的缺点?我不知道为什么我得到一个空字符串值而不是“HB Woodlawn”
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
</head>
<body>
<script type="text/babel">
// Editing one object in an array of objects
let schools = [
{name: 'Yorktown'},
{name: 'Stratford'},
{name: 'Washington & Lee'},
{name: 'Wakefield'}
];
const editName = (oldName, newName, arr) =>
arr.map(item => {
if (item.name === oldName) {
return {
...item,
name
}
}
else {
return item
}
});
let updatedSchools = editName('Stratford', 'HB Woodlawn', schools);
console.log(updatedSchools[1]); // name: ""
console.log(schools[1]); // name: "Stratford"
</script>
</body>
</html>
let schools = [
{name: 'Yorktown'},
{name: 'Stratford'},
{name: 'Washington & Lee'},
{name: 'Wakefield'}
];
const editName = (oldName, newName, arr) =>
arr.map(item => {
if (item.name === oldName) {
return {
...item,
name: newName
}
}
else {
return item
}
});
let updatedSchools = editName('Stratford', 'HB Woodlawn', schools);
console.log(updatedSchools[1]); // name: ""
console.log(schools[1]); // name: "Stratford"
您没有为名称添加新值,而是将其留空。添加了name:newName
你当然不需要这样做:
...item,
name: newName
一旦你进行了传播复制,并保持它是纯函数,你就可以只返回新值,map将从回调函数中获取它。
所以,对你的问题更好的答案是,你真的在那里写错字,写名字而不是新名字。这个变量在书中被称为名称,然后一旦你重写了这个函数,你就忘记了它的全部内容:)。
只需改变线条;
return {
...item,
name
}
至
return {
...item,
newName
}
这更干净:)。