react 渲染道具_在React中学习分解道具的基础

react 渲染道具

by Evelyn Chan

通过伊芙琳·陈

在React中学习分解道具的基础 (Learn the basics of destructuring props in React)

When I first learned about ES6, I was hesitant to start using it. I’d heard a lot of great things about the improvements but at the same time, I’d just gotten used to the good ol’ original way of doing things and here was a new syntax thrown at me to learn.

当我第一次了解ES6时,我犹豫要开始使用它。 我听到了很多有关改进的很棒的事情,但是与此同时,我只是习惯了良好的原始工作方式,这是我学习的一种新语法。

I avoided it for a while under the premise of “if it ain’t broke don’t fix it,” but I’ve recently grown fond of its simplicity and the fact that it’s becoming the norm in JavaScript.

我曾在“如果它还没有坏,就不修复它”的前提下避免了一段时间,但是我最近对它的简单性以及它已经成为JavaScript的规范感到很喜欢。

With React, which fully embraces the ES6 syntax, destructuring adds a slew of benefits to improving your code. This article will go over the basics of destructuring objects and how it applies to props in React.

使用完全包含ES6语法的React,解构可以为改进代码带来很多好处。 本文将介绍解构对象的基础知识以及如何将其应用于React中的props。

破坏的原因 (Reasons to destructure)

提高可读性 (Improves readability)

This is a huge upside in React when you’re passing down props. Once you take the time to destructure your props, you can get rid of props / this.props in front of each prop.

当您传递道具时,这在React中是巨大的优势。 一旦您花时间破坏了道具,就可以在每个道具的前面摆脱props / this.props

If you’re abstracting your components into different files, you’ll also have a handy place to quickly reference what props you’re passing down without having to switch tabs. This double check helps you catch errors such as passing down excess props or typos.

如果要将组件抽象到不同的文件中,则还可以方便地快速引用要传递的道具,而无需切换选项卡。 这项双重检查可帮助您捕获错误,例如传递过多的道具或错别字。

You can go a step further by adding in propType validation, which allows you to define the type of each prop you pass in. When you’re in a development environment, this triggers React to log a warning if the type is different from the one defined.

您可以通过添加propType验证来propType ,它允许您定义传入的每个prop的类型。在开发环境中时,如果类型不同于一个,则触发React记录警告。定义。

Props can be difficult to keep track of in complex apps, so clearly defining your props as you pass them down is immensely helpful for anyone reading your code.

在复杂的应用程序中,道具可能很难跟踪,因此在向下传递道具时清楚地定义道具对于任何阅读代码的人都非常有帮助。

较短的代码行 (Shorter lines of code)

See the following before ES6:

在ES6之前,请参阅以下内容:

var object = { one: 1, two: 2, three: 3 }
var one = object.one;var two = object.two;var three = object.three
console.log(one, two, three) // prints 1, 2, 3

It’s long, clunky, and takes way too many lines of code. With destructuring, your code becomes much more clear.

它很长,很笨拙,并且占用了太多的代码行。 通过解构,您的代码变得更加清晰。

In the example below, we’ve effectively cut down the number of lines to two:

在下面的示例中,我们有效地将行数减少为两行:

let object = { one: 1, two: 2, three: 3 }
let { one, two, three } = object;
console.log(one, two, three) // prints 1, 2, 3
句法糖 (Syntactic sugar)

It makes code look nicer, more succinct, and like someone who knows what they’re doing wrote it. I’m somewhat reiterating the first point here, but then again if it improves readability, why wouldn’t you do it?

它使代码看起来更好,更简洁,就像知道自己在做什么的人一样。 我在这里重申了第一点,但是如果它提高了可读性,那么再来一次,您为什么不这样做呢?

功能与类组件 (Functional vs. Class Components)

Destructuring in React is useful for both functional and class components but is achieved just a tad bit differently.

React中的解构对于功能组件和类组件都是有用的,但是在实现上却有所不同。

Let’s consider a parent component in our application:

让我们考虑一下应用程序中的父组件:

import React, { Component } from 'react';
class Properties extends Component {  constructor() {    super();    this.properties = [      {        title: 'Modern Loft',        type: 'Studio',        location: {          city: 'San Francisco',          state: 'CA',          country: 'USA'        }      },      {        title: 'Spacious 2 Bedroom',        type: 'Condo',        location: {          city: 'Los Angeles',          state: 'CA',          country: 'USA'        }      },    ];  }
render() {    return (      <div>        <Listing listing={this.properties[0]} />        <Listing listing={this.properties[1]} />      </div>    );  }}
功能组件 (Functional Components)

In this example, we want to pass down a listing object from our array of properties for the child component to render.

在此示例中,我们希望从属性数组中传递一个listing对象,以供子组件呈现。

Here’s how a functional component would look:

这是功能组件的外观:

const Listing = (props) => (  <div>    <p>Title: {props.listing.title}</p>    <p>Type: {props.listing.type}</p>    <p>      Location: {props.listing.location.city},      {props.listing.location.state},      {props.listing.location.country}    </p>  </div>);

This block of code is fully functional but looks terrible! By the time we get to this Listing child component, we already know we’re referencing a listing, so props.listing looks and feels redundant. This block of code can be made to look much cleaner through destructuring.

此代码块功能齐全,但看起来很糟糕! 当我们到达这个Listing子组件时,我们已经知道我们正在引用一个清单,因此props.listing看起来和感觉都是多余的。 通过解构,可以使这段代码看起来更简洁。

We can achieve this in the function parameter as we pass in the props argument:

我们可以在传递props参数时在function参数中实现此目的:

const Listing = ({ listing }) => (  <div>    <p>Title: {listing.title}</p>    <p>Type: {listing.type}</p>    <p>      Location: {listing.location.city},      {listing.location.state},      {listing.location.country}    </p>  </div>);

Even better, we can further destructure nested objects like below:

更好的是,我们可以进一步分解嵌套对象,如下所示:

const Listing = ({  listing: {    title,    type,    location: {      city,      state,      country    }  }}) => (  <div>    <p>Title: {title}</p>    <p>Type: {type}</p>    <p>Location: {city}, {state}, {country}</p>  </div>);

Can you see how much easier this is to read? In this example, we’ve destructured both listings and the keys inside listing.

您能看到这更容易阅读吗? 在此示例中,我们对listingslistings的键进行了listing

A common gotcha is destructuring only the keys like we do below and trying to access the object:

一个常见的陷阱是仅对键进行解构,就像我们在下面所做的那样,并尝试访问该对象:

{ location: { city, state, country } }

In this scenario, we wouldn’t be able to access the location object through a variable named location.

在这种情况下,我们将无法通过名为location的变量访问location对象。

In order to do so, we’d have to define it first with a simple fix like so:

为了做到这一点,我们必须首先用一个简单的解决方法定义它,如下所示:

{ location, location: { city, state, country } }

This wasn’t glaringly obvious to me at first, and I’d occasionally run into problems if I wanted to pass an object like location as a prop after destructuring its contents. Now you’re equipped to avoid the same mistakes I made!

一开始这对我来说并不是显而易见的,而且如果我想在分解内容之后将location类的对象作为道具传递给我,偶尔会遇到麻烦。 现在您已准备好避免我犯的相同错误!

类组件 (Class Components)

The idea is very much the same in class components, but the execution is a little different.

这个想法在类组件中几乎是相同的,但是执行有些不同。

Take a look below:

看下面:

import React, { Component } from 'react';
class Listing extends Component {  render() {    const {      listing: {        title,        type,        location: {          city,          state,          country        }      }    } = this.props;
return (      <div>        <p>Title: {title}</p>        <p>Type: {type}</p>        <p>          Location: {city}, {state}, {country}        </p>      </div>    )  }}

You may have noticed in the parent example that we can destructure the Component object as we import React in class components. This isn’t necessary for functional components as we won’t be extending the Component class for those.

您可能已经在父示例中注意到,当我们在类组件中导入React ,我们可以对Component对象进行解构。 对于功能组件,这不是必需的,因为我们不会为这些Component扩展Component类。

Next, instead of destructuring in the argument, we destructure wherever the variables are being called. For example, if we take the same Listing child component and refactor it into a class, we would destructure in the render function where the props are being referenced.

接下来,我们将在调用变量的任何位置进行销毁,而不是对参数进行销毁。 例如,如果我们使用相同的Listing子组件并将其重构为一个类,我们将在引用道具的render函数中对结构进行分解。

The downside to destructuring in class components is that you’ll end up destructuring the same props each time you use it in a method. Although this can be repetitive, I’d argue that a positive is it clearly outlines which props are being used in each method.

在类组件中进行结构分解的不利之处在于,每次在方法中使用它时,最终都会破坏相同的道具。 尽管这可能是重复的,但我认为肯定的是,它清楚地概述了每种方法中使用的道具。

In addition, you won’t have to worry about side effects such as accidentally changing a variable reference. This method keeps your methods separate and clean, which can be a huge advantage for other operations during your projects such as debugging or writing tests.

此外,您不必担心副作用,例如意外更改变量引用。 此方法使您的方法保持独立和整洁,这对于项目中的其他操作(例如调试或编写测试)可能是一个巨大的优势。

Thanks for reading! If this helped you, please clap and/or share this article so it can help others too! :)

谢谢阅读! 如果这对您有帮助,请拍手和/或分享此文章,以便对他人也有所帮助! :)

翻译自: https://www.freecodecamp.org/news/the-basics-of-destructuring-props-in-react-a196696f5477/

react 渲染道具

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值