简体   繁体   中英

How to check if element exists in map() React

I have working code

const products = this.state.products.map((product, i) => 
        product.fields.company.fields.slug === this.props.match.params.slug ?
        <Suspense key={i} fallback={<div>Loading...</div>}>
            <ProductListItem id={i} key={i} product={product} />
        </Suspense>
        : null)

        return(
            <div className="partner-details" style={partnerD}>
                <div className="container-xl">
                    <Button type="button" className="btn btn-secondary" onClick={this.props.history.goBack}>
                        <i className="fa fa-arrow-left"></i>&nbsp; Get back
                    </Button>
                    <ul>
                        <div className="product-item">
                            {products}
                        </div>
                    </ul>
                </div>
            </div>             
        )

But the problem is if product.fields.company.fields.slug (company.fields.slug) does not exist my code crashes. How can I add extra ternary operator to check if it product.fields.company exist before execute this product.fields.company.fields.slug === this.props.match.params.slug

Thanks!

In line 2 you can do: (product && product.fields && product.fields.company && product.fields.company.fields && product.fields.company.fields.slug && this.props && this.props.match && this.props.match.params && this.props.match.params.slug && product.fields.company.fields.slug === this.props.match.params.slug) ?

or use optional chaining .

Use optional-chaining ( Babel plugin )

product.fields?.company?.fields?.slug

Or make use of the || operator :

(((product.fields || {}).company || {}).fields || {}).slug

And consider wrapping your compoennt in an error boundary so your app won't crash when there's this kind of errors.

if your environment has support for optional chaining you can do this

product?.fields?.company?.fields?.slug === this.props.match.params.slug ?  .. : ..

otherwise you need to check that each field is truthy

product && product.fields && product.fields.company && product.fields.company.fields && product.fields.company.fields.slug === this.props.match.params.slug ? .. : ..

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