gpt4 book ai didi

javascript - React 中花括号内的花括号

转载 作者:行者123 更新时间:2023-11-30 20:15:47 25 4
gpt4 key购买 nike

我在 React 中有展示组件。使用 products.some 我正在尝试检查是否检查了 products 中的任何项目。如果选中了某些项目,则呈现 RequestedProduct 组件的父 block 。我知道问题是第二对花括号,因为 React 认为它是一个 Prop 。还有其他方法吗?

const Requested = ({ products, getCurrentTime }) => (
<div className="pepper-pin-body-tab requested-tab">
<div className="pepper-pin-body-tab-title">
Запрошенные
</div>
<div className="pepper-pin-body-tab-indicator" />
{products.some(product => product.checked) ? (
<div className="requested-tab-list-requested">
<div className="requested-tab-list-requested-time">
{getCurrentTime()}
</div>
{products.filter((product, key) => {
if (product.checked) {
return (
<RequestedProduct
key={key}
title={product.title}
/>
);
}
})}
</div>
) : null}
</div>
);

最佳答案

问题是,filter不会返回自定义元素/值,它将始终返回您从过滤器主体返回 true 的数组元素。

解决方案是,只使用 map 或过滤器和 map 的组合。

使用 map :

{
products.map((product, key) => product.checked ?
<RequestedProduct key={key} title={product.title} />
: null
}

使用过滤器和映射的组合:

{
products
.filter(product => product.checked)
.map((product, key) => <RequestedProduct key={key} title={product.title}/>)
}

检查这个片段,你会得到一个更好的主意:

const arr = [
{a: 1},
{a: 2},
{a: 3},
{a: 4}
];

const afterFilter = arr.filter((el,i) => {
if(i%2) {
return `Hello world ${i}`;
}
});

// it will print the array items, not the Hello World string
console.log('afterFilter', afterFilter);

关于javascript - React 中花括号内的花括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51929068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com