简体   繁体   中英

React - Loop inside a loop not rendering

I have a map loop inside another loop like this:

{"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>)
        })
    }
})}

The console works, but not the render. Any idea why?

Thank you

The problem here that outer .map doesn't have return statement and your outer code doesn't have return statement too.

So you have to change your code to the following

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

Also some notes on how you can make your code more readable with new es6 features. Commented version

// 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>)
    })
  }
})

Final version:

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

NOTE to use all of them in all common browser you have to configure your babel properly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM