reactjs filteredfruitData.map 不是函数-React错误

j2qf4p5b  于 2023-02-18  发布在  React
关注(0)|答案(5)|浏览(140)

我有以下fruitData

const fruitData = [{ fruitname: 'apple', fruitprice: '200', fruitcolor: 'red'},
{ fruitname: 'mango', fruitprice: '500', fruitcolor: 'yellow'},
{ fruitname: 'berry', fruitprice: '300', fruitcolor: 'red'}];

在下面的返回部分中,我试图检查fruitData中哪些水果的颜色为“红色”。

return (
<section>
  {fruitData.map((info) => {
    if (info.fruitcolor === ‘red’) {
 // return filtered fruit data
      return null;
    }

你能帮我我应该如何返回过滤水果数据。我希望它是在下面的格式

const filteredfruitData = [{ fruitname: 'apple', fruitprice: '200', fruitcolor: 'red'},

{ fruitname: 'berry', fruitprice: '300', fruitcolor: 'red'}];
vtwuwzda

vtwuwzda1#

在这个场景中应该使用filter方法,

return (
    <section>
      {fruitData
        .filter((fruit) => fruit.fruitcolor === "red")
        .map((info) => (
          <span>{info.fruitname} </span>
        ))}
    </section>
  );

Check demo

e4eetjau

e4eetjau2#

使用filter方法过滤red颜色

const filteredData = fruitData.filter((fruit) => fruit.fruitcolor === "red")
console.log(filteredData);
vhipe2zx

vhipe2zx3#

给你!

function App() {
const fruitData = [{ fruitname: 'apple', fruitprice: '200’, fruitcolor: ‘red’},
{ fruitname: 'mango', fruitprice: '500’, fruitcolor: ‘yellow’},
{ fruitname: ’berry', fruitprice: ‘300’, fruitcolor: ‘red’}]

const filteredFruits = fruitData.filter((item) => item.fruitcolor === "red")

return (
<section>
  {filteredFruits.map((fruit) => {
   // Your code
   })}
</section>
)
}
export default App;
8xiog9wr

8xiog9wr4#

嘿,你可以尝试使用数组方法Map来复制你的数据并显示结果。

const fruitData = [
    { fruitname: "apple", fruitprice: "200", fruitcolor: "red"},
    { fruitname: 'mango', fruitprice: '500', fruitcolor: 'yellow'},
    { fruitname: 'berry', fruitprice: '300', fruitcolor: 'red'},
];
return (
 <section>
   {fruitData.map((data) => {
     if (data.fruitcolor === "red") return data;
   })}
</section>
)
jaql4c8m

jaql4c8m5#

在使用Array.map()方法时,可以避免添加任何转义逻辑,而是在使用Array.map()之前使用Array.filter()方法。

const fruitData = [{
    fruitname: "apple",
    fruitprice: "200",
    fruitcolor: "red"
  },
  {
    fruitname: "mango",
    fruitprice: "500",
    fruitcolor: "yellow"
  },
  {
    fruitname: "berry",
    fruitprice: "300",
    fruitcolor: "red"
  },
];

const filteredFruitData = fruitData.filter(
  ({
    fruitcolor
  }) => fruitcolor === "red"
);

console.log("filteredFruitData", filteredFruitData);

相关问题