我有一个对象值数组,每个对象值都有自己的对象子数组。
我正在尝试使用 Array.find() 方法专门针对每个数组节点,并根据名称从它的子数组中返回一个值。
我的函数都写出来了,但没有返回任何内容,我不断收到警告,说明:
Expected to return a value at the end of the function(array-callback-return)
而且我不完全确定我错过了什么。
供参考的函数和数据结构以及一个CodeSandbox:
const subjectTypes = [
{
name: "pokemon",
details: [
{
type: "subtitle",
value: "This is the subtitle for pokemon"
}
]
},
{
name: "marvel",
details: [
{
type: "subtitle",
value: "This is the subtitle for marvel"
}
]
}
];
const setCustomValue = (location) => {
let value;
switch (location) {
case "/pokemon":
return (value = subjectTypes.find(function (subject, idx) {
if (subject.name === "pokemon") return subject.details.value;
}));
case "/marvel":
return (value = subjectTypes.find(function (subject, idx) {
if (subject.name === "marvel") return subject.details.value;
}));
default:
return null;
}
};
const customValue = setCustomValue("/pokemon");
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Dynamically Populated Content Below:</h2>
<p>{customValue}</p>
</div>
);
}
另外我知道这可能看起来像过度工程,我可以很容易地使用 .map() 或类似的来打印值,但我将其用作我正在尝试解决的更大问题的简化版本解决需要类似 .find() 方法来返回特定结果的方法。
Array#find()
期待一个true
orfalse
来自回调。或者至少是一个真值或假值。
ESLint 规则array-callback-return报告了一个相关问题。回调只从 返回一些东西if
,而不是在不满足条件时。这通常是有效的- noreturn
使函数隐式返回undefined
。由于该值为假,find
将忽略此项并继续下一项。然而,ESLint 规则是为了使这些返回明确并防止错误,以防它实际上是一个代码分支不返回任何内容的错误。
在回调中,返回值是subject.details.value
但实际路径是subject.details[0].value
因为subject.details
是一个数组。因此,您唯一的回报是产生undefined
.
不可能同时定位一个值.find()
并修改返回的值。你需要返回值第一,然后得到它的一个子部分。
value
从不使用时无需声明和分配。
为了解决这些问题,这里的代码有点清理:
const setCustomValue = (location) => {
let value;
switch (location) {
case "/pokemon":
value = subjectTypes.find(function (subject, idx) {
return subject.name === "pokemon";
});
return value.details[0].value;
case "/marvel":
value = subjectTypes.find(function (subject, idx) {
return subject.name === "pokemon";
});
return value.details[0].value;
default:
return null;
}
};
为了避免一些重复,您可以提取.find()
和return
之外的逻辑switch
:
const setCustomValue = (location) => {
let name;
switch (location) {
case "/pokemon":
name = "pokemon";
break;
case "/marvel":
name = "marvel";
break;
default:
return null;
}
const value = subjectTypes.find((subject) => subject.name === name);
return value.details[0].value;
};
switch
可以通过使用简单的查找来消除整体:
const paths = {
"/pokemon": "pokemon",
"/marvel": "marvel",
}
const setCustomValue = (location) => {
let name = paths[location];
if (!name)
return null;
const value = subjectTypes.find((subject) => subject.name === name);
return value.details[0].value;
};
const paths = {
"/pokemon": "pokemon",
"/marvel": "marvel",
}
const setCustomValue = (location) =>
subjectTypes.find((subject) => subject.name === paths[location])?.details[0].value ?? null;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句