简体   繁体   中英

Conditional rendering React issue (loop)

I was trying to use forEach or map functions with no success (had xxx is not a function errors). Decided to go with good old for loop but instead of creating multiple div elements my program only renders one.

Simplified example:

getTest(){
    const l = this.props.renderedDrugs.length;

    for(var i = 0; i < l; i++){
        return <div>{this.props.renderedDrugs[i].id}</div>
    }
}

render() {

    const test = (this.props.renderedDrugs) ? this.getTest() : nope()

    function nope(){
        return 'nope'
    }
    return (
        <div>{test}</div>
    )
}
}

No matter what I do I cant return multiple divs, have no problems with multiple console logs though. Am I missing something crucial from basic react functions that I completely forgot because of staring at the screen like a moron?

You do want map :

getTest() {
    return this.props.renderedDrugs.map(rd => <div>{rd.id}</div>)
}

The reason only one renders is because return <div>{this.props.renderedDrugs[i].id}</div> , ya know, returns that value from the function. map is a lot cleaner but you can emulate map with your for loop and an array:

getTest(){
    const l = this.props.renderedDrugs.length;
    const ary = [];

    for(var i = 0; i < l; i++){
        ary.push(<div>{this.props.renderedDrugs[i].id}</div>);
    }
    return ary;
}

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