简体   繁体   English

在 ReactJS 传递道具

[英]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.以下是我在 React 组件中的 JSX 代码,它运行良好并且目前正在使用中,但在大多数 React 博客文章中,它们也在解构 object。我的问题是 - 将代码修改为版本 2 是否有任何额外好处或者这很好。

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.这与解构没什么关系,除了解构迫使你有一个 function 主体和明确的回报。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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