反应-循环内部循环不渲染

时间:2019-10-09 14:47:45

标签: reactjs loops render

我在另一个这样的循环中有一个map循环:

{"undefined" !== typeof this.props.categoryObject['products'] && Object.keys(this.props.categoryObject['products']).length > 0 && Object.keys(this.props.categoryObject['products']).map(keyProd => {
    const product = this.props.categoryObject['products'][keyProd];
    if("undefined" !== typeof product) {
        Object.keys(this.props.activeFilters).map(keyFilter => {     
            console.warn(this.props.activeFilters[keyFilter]);
            return (<div>test</div>)
        })
    }
})}

控制台可以工作,但渲染不起作用。知道为什么吗?

谢谢

1 个答案:

答案 0 :(得分:0)

这里的问题是外部.map没有return语句,而外部代码也没有return语句。

因此您必须将代码更改为以下内容

return ("undefined" !== typeof this.props.categoryObject['products'] && Object.keys(this.props.categoryObject['products']).length > 0 && Object.keys(this.props.categoryObject['products']).map(keyProd => {
    const product = this.props.categoryObject['products'][keyProd];
    if("undefined" !== typeof product) {
        return Object.keys(this.props.activeFilters).map(keyFilter => {     
            console.warn(this.props.activeFilters[keyFilter]);
            return (<div>test</div>)
        })
    }
}))

关于使用es6的新功能如何使代码更具可读性的一些说明。评论版本

// It's better to extract products into separate variable 
// as there are a lot of copy paste code for this action
const { products } = this.props.categoryObject;

// `undefined` is falsy value so you can just test next condition for early exit
if (!products) { return null; }

// 1. no need to test for `.length` as iterating empty array will make 0 iterations
// 2. use Object.entries you can immediately get key and value
return Object.entries(products).map(([key, product]) => {
  // Same things as with `products` variable
  if (product) {
    // I think for your future code you can use `Object.entries` here too
    return Object.keys(this.props.activeFilters).map(keyFilter => {     
      return (<div>test</div>)
    })
  }
})

最终版本:

const { products } = this.props.categoryObject;
if (!products) { return null; }

return Object.entries(products).map(([key, product]) => {
  if (product) {
    return Object.keys(this.props.activeFilters).map(keyFilter => {     
      return (<div>test</div>)
    })
  }
})

注意,要在所有通用浏览器中使用所有这些,您必须正确配置babel