[英]Mapping thru state object and testing multiple nested arrays without multiple return values?
我(显然)对 React 和 Javascript 很陌生,所以如果这是一个愚蠢的问题,请提前道歉。 基本上我在 this.state 中有一个对象数组,每个对象都有自己的嵌套数组,如下所示:
foods: [
{
type: "sandwich",
recipe: ["bread", "meat", "lettuce"]
},
{
type: "sushi",
recipe: ["rice", "fish", "nori"]
}, ...
我已经编写了一个 function 映射通过 state 对象和每个 object.recipe 上的 runs.includes() 以查看它是否包含字符串。
const newArray = this.state.foods.map((thing, i) => {
if (thing.recipe.includes(this.state.findMe)) {
return <p>{thing.type} contains {this.state.findMe}</p>;
} return <p>{this.state.findMe} not found in {thing.type}</p>;
});
主要问题是 that.map() 为数组中的每个项目返回一个值,我不希望这样。 我需要一个 function 来检查每个 object.recipe,如果找到一个匹配项(如上所示),则返回一个匹配项,但如果嵌套 ZA3CBC3F9D0CE2F2C159CZD 的值包含 71D6 则返回“未找到匹配项”消息。 现在这个 function 为数组中的每个 object 返回“{this.state.findMe} not found in {thing.type}”。
我知道.map() 应该返回一个值。 我尝试使用 forEach() 和 .filter() 代替,但我无法使语法正常工作。 (我也不知道如何使这个 function 成为无状态的功能组件——我只能把它放在 render() 方法中才能让它工作——但这不是我真正的问题。)
class App extends React.Component {
state = {
foods: [
{
type: "sandwich",
recipe: ["bread", "meat", "lettuce"]
},
{
type: "sushi",
recipe: ["rice", "fish", "nori"]
},
{
type: "chili",
recipe: ["beans", "beef", "tomato"]
},
{
type: "padthai",
recipe: ["noodles", "peanuts", "chicken"]
},
],
findMe: "bread",
}
render() {
const newArray = this.state.foods.map((thing, i) => {
if (thing.recipe.includes(this.state.findMe)) {
return <p>{thing.type} contains {this.state.findMe}</p>;
} return <p>{this.state.findMe} not found in {thing.type}</p>;
});
return (
<div>
<div>
<h3>Results:</h3>
{newArray}
</div>
</div>
)
}
};
您可以为此使用Array.reduce
:
const result = foods.reduce((acc,curr)=> curr.recipe.includes(findMe) ? `${curr.type} contains ${findMe}`:acc ,'nothing found')
console.log(result)
虽然如果在不止一个配方中找到该成分,它只会返回最后一个。
或者,您可以使用map
和filter
:
const result = foods.map((thing, i) => {
if (thing.recipe.includes(findMe)) {
return `${thing.type} contains ${findMe}`;
}}).filter(val=>!!val)
console.log(result.length?result[0]:'nothing found')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.