React中的花括号内嵌花括号

3

我在React中有一个展示组件。使用products.some检查是否选中了products中的任何项目。如果选中了某个项目,则渲染RequestedProduct组件的父块。我知道问题在于第二对花括号,因为React认为它是一个属性。还有其他方法可以解决这个问题吗?

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>
);

它是否打印了任何错误? - Imesh Chandrasiri
你指的是哪一行有问题? - Bhojendra Rauniyar
2个回答

3
问题在于,filter 不会返回自定义元素或值,它总是返回你从 filter 函数体中返回 true 的数组元素。
解决方案是,只使用 map 或结合使用 filter 和 map。
使用 map:
{
    products.map((product, key) => product.checked ? 
        <RequestedProduct key={key} title={product.title} /> 
        : null
}

使用filter和map的组合:

{
    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);


感谢您的帮助和解释。 - Kitty Captain
很高兴能帮到你 :) - Mayank Shukla

0
我建议将代码分割一下,这样可以使意图更加清晰。例如,你最终会得到以下代码,不应该触发错误。
主要问题在于过滤器的非预期副作用,而你很可能想使用一个filter和一个map。这样可以使另一个开发人员更加清楚地了解你的意图。
const contents = (products, getCurrentTime) => (
    const filtered = products.filter(product => product.checked);
    <div className="requested-tab-list-requested">
        <div className="requested-tab-list-requested-time">
            {getCurrentTime()}
        </div>
        {filtered.map((product, key) => <RequestedProduct key={key} title={product.title}/>)}
    </div>  
);

const Requested = ({products, getCurrentTime}) => {
    const isAnythingChecked = products.some(product => product.checked);

    return <div className="pepper-pin-body-tab requested-tab">
        <div className="pepper-pin-body-tab-title">
            Запрошенные
        </div>
        <div className="pepper-pin-body-tab-indicator"/>
        {isAnythingChecked ? contents(products, getCurrentTime) : null}
    </div>
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接