简体   繁体   中英

Is there a workaround as to how to return inside a conditional statement in a React component?

I am trying to solve a problem that I've already done with jQuery but trying to teach myself React at the same time and redoing the solution doesn't seem to be as smooth as I thought - what a surprise. Anyways just for now I'm trying to output a list of the items and prices onto my React app but I cannot get it to return JSX inside of the if statement.

I understand JSX has issues at run time with if statements but I have tried ternary operators as well and I cannot find a work around. When I try the ternary operation I get an error on my return statement saying 'expression expected' .

        this.state.itemsWithPrice.map(x =>
            data.map(n => {
                if(n==x.market_hash_name){
                    // alert(x.market_hash_name+x.price);
                    return (
                        <li>{x.price}</li>
                    )
                }
        }))

       return <h1>works here</h1>  

So pretty much the data array has the names of the items I am interested in and itemsWithPrice has the names + additional information so I am trying to only return the items of interest which is why I need to return inside the if (x.price and more after I figure out how). Is there a work around for this?

filter does that.

data
    .filter(n => fulfillsSomeCondition(n)) // other n are just removed from further consideration
    .map(n => <li>some content</li>)

You can filter the data before returning:

const filteredData = this.state.itemsWithPrice.map(x => data.includes(x.market_hash_name));

filteredData.map(n => <li>{x.price}</li>); 

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