简体   繁体   中英

Passing of Props in ReactJS

Following is my JSX code in a React component which is working fine and currently in use, but in most of React blog posts they are also de structuring an object. My query is - do we have any extra benefit of modifying the code to Version 2 or this is just fine.

First Version (currently in use) -

const CartItems = ({ items }) => items.length ? items.map((x, i) => (
    <div key={x.id} className={`cart-item-${i}`}>
      <div className="card ">
        <div className="cart-item-img">
            <img src={x.url} alt={x.altText} className="img" />
        </div>
        <div className="cart-item-desc">
            <h3 className="title">{x.title}</h3>
            <p className="text">{x.shortDesc}</p>
        </div>
        <div className="cart-item-action">
            <button className="add">+</button>
            <button className="subtract">-</button>
            <button className="remove">X</button>
        </div>
      </div>
    </div>)) : []

2nd Version -

const CartItems = ({ items }) => items.length ? items.map((x, i) => {
    const {
        id,
        url,
        altText,
        title,
        shortDesc
    } = x;
    return (
    <div key={id} className={`cart-item-${i}`}>
      <div className="card ">
        <div className="cart-item-img">
            <img src={url} alt={altText} className="img" />
        </div>
        <div className="cart-item-desc">
            <h3 className="title">{title}</h3>
            <p className="text">{shortDesc}</p>
        </div>
        <div className="cart-item-action">
            <button className="add">+</button>
            <button className="subtract">-</button>
            <button className="remove">X</button>
        </div>
      </div>
    </div>)
    }) : []

The benefits are mostly aesthetic and subjective, so if you prefer the first one, more power to you and nothing that says you need to change it.

My personal view on the two snippets you posted: I tend to avoid direct returns from arrow functions because I'll oftentimes need to add a log or something else and having to convert back and forth eventually wears on you. This has little to do with the destructuring though, other than destructuring forces you to have a function body and explicit return.

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