Programing

React에서이 세 점은 무엇을합니까?

lottogame 2020. 9. 30. 08:39
반응형

React에서이 세 점은 무엇을합니까?


은 무엇 않는 ...코드와 어떤 (JSX를 사용하는 것은)이라고 반응이에 무엇입니까?

<Modal {...this.props} title='Modal heading' animation={false}>

그것이 재산 확산 표기법 입니다. ES2018에 추가되었지만 트랜스 파일을 통해 React 프로젝트에서 오랫동안 지원되었습니다 (속성뿐만 아니라 다른 곳에서도 할 수 있더라도 "JSX 스프레드 속성"으로).

{...this.props} 밖으로 스프레드 에서 "자신의"속성 props상의 개별 속성으로 Modal당신이 만드는 요소입니다. 예를 들어, 경우는 this.props포함 a: 1하고 b: 2다음,

<Modal {...this.props} title='Modal heading' animation={false}>

다음과 같을 것입니다

<Modal a={this.props.a} b={this.props.b} title='Modal heading' animation={false}>

그러나 동적이므로 "자신의"속성이 무엇이든 props포함됩니다.

이후 children에 "자신의"속성입니다 props, 스프레드가 포함됩니다. 따라서 이것이 표시되는 구성 요소에 자식 요소가 있으면 Modal. 여는 태그와 닫는 태그 사이에 자식 요소를 넣는 것은 여는 태그에 children속성 을 넣는 데 유용한 구문상의 설탕 일뿐 입니다. 예:

class Example extends React.Component {
  render() {
    const { className, children } = this.props;
    return (
      <div className={className}>
      {children}
      </div>
    );
  }
}
ReactDOM.render(
  [
    <Example className="first">
      <span>Child in first</span>
    </Example>,
    <Example className="second" children={<span>Child in second</span>} />
  ],
  document.getElementById("root")
);
.first {
  color: green;
}
.second {
  color: blue;
}
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

확산 표기법은 해당 사용 사례뿐만 아니라 기존 객체의 속성 대부분 (또는 전체)을 사용하여 새 객체를 만드는 데 유용합니다. 상태를 수정할 수 없기 때문에 상태를 업데이트 할 때 많이 나타납니다. 직접:

this.setState(prevState => {
    return {foo: {...prevState.foo, a: "updated"}};
});

이는 this.state.foo다음과 같은 속성을 foo제외하고 모든 속성이 동일한 새 개체로 대체 a됩니다 "updated".

const obj = {
  foo: {
    a: 1,
    b: 2,
    c: 3
  }
};
console.log("original", obj.foo);
// Creates a NEW object and assigns it to `obj.foo`
obj.foo = {...obj.foo, a: "updated"};
console.log("updated", obj.foo);
.as-console-wrapper {
  max-height: 100% !important;
}


아시다시피 ...라고 확산 속성 이름은 식 확장 할 수 있습니다 나타냅니다.

var parts = ['two', 'three'];
var numbers = ['one', ...parts, 'four', 'five']; // ["one", "two", "three", "four", "five"]

그리고이 경우 (간단하게하겠습니다).

//just assume we have an object like this:
var person= {
    name: 'Alex',
    age: 35 
}

이:

<Modal {...person} title='Modal heading' animation={false} />

와 동등하다

<Modal name={person.name} age={person.age} title='Modal heading' animation={false} />

간단히 말해서 깔끔한 지름길 이라고 말할 수 있습니다 .


세 개의 점은 ES6 스프레드 연산자나타냅니다 . Javascript에서 몇 가지 작업을 수행 할 수 있습니다.

  1. 배열 연결

    var shooterGames = ['Call of Duty', 'Far Cry', 'Resident Evil' ];
    var racingGames = ['Need For Speed', 'Gran Turismo', 'Burnout'];
    var games = [...shooterGames, ...racingGames];
    
    console.log(games)  // ['Call of Duty', 'Far Cry', 'Resident Evil',  'Need For Speed', 'Gran Turismo', 'Burnout']
    
  2. 배열 분해

      var shooterGames = ['Call of Duty', 'Far Cry', 'Resident Evil' ];
      var [first, ...remaining] = shooterGames;
      console.log(first); //Call of Duty
      console.log(remaining); //['Far Cry', 'Resident Evil']
    
  3. 배열로 함수 인수

     function fun1(...params) { 
    
     }  
    

위의 매개 변수는 나머지 매개 변수로 알려져 있으며 함수에 전달되는 값의 수를 제한하지 않습니다. 그러나 인수는 동일한 유형이어야합니다.

  1. 두 개체 결합

    var myCrush = {
      firstname: 'Selena',
      middlename: 'Marie'
    };
    
    var lastname = 'my last name';
    
    var myWife = {
      ...myCrush,
      lastname
    }
    
    console.log(myWife); // {firstname: 'Selena',
                         //   middlename: 'Marie',
                         //   lastname: 'my last name'}
    

JavaScript의 세 점은 spread / rest 연산자 입니다.

스프레드 연산자

확산 구문은 표현식이 여러 인수가 예상되는 장소에서 확장 할 수 있습니다.

myFunction(...iterableObj);

[...iterableObj, 4, 5, 6]

[...Array(10)]

나머지 매개 변수

나머지 파라미터 구문 인수 가변 수의 기능을 위해 사용된다.

function(a, b, ...theArgs) {
  // ...
}

어레이에 대한 확산 / 나머지 연산자는 ES6에서 도입되었습니다. 개체 확산 / 휴식 속성에 대한 State 2 제안 이 있습니다.

TypeScript는 또한 확산 구문을 지원하며 사소한 문제 로 이전 버전의 ECMAScript로 변환 할 수 있습니다 .


이것은 React에서도 사용되는 es6의 기능입니다. 아래 예를보십시오.

function Sum(x,y,z) {
   return x + y + z;
}
console.log(Sum(1,2,3)); //6

이 방법은 최대 3 개의 매개 변수가있는 경우에는 괜찮지 만 예를 들어 110 개의 매개 변수를 추가해야하는 경우에는 어떨까요? 모두 정의하고 하나씩 추가해야할까요?! 물론 SPREAD라고하는 더 쉬운 방법이 있습니다. 모든 매개 변수를 전달하는 대신 작성합니다.

function (...numbers){} 

우리는 얼마나 많은 매개 변수를 가지고 있는지 알지 못하지만 그것들의 힙이 있다는 것을 압니다. es6를 기반으로 위의 함수를 아래와 같이 다시 작성하고 스프레드와 매핑을 사용하여 케이크 조각처럼 쉽게 만들 수 있습니다.

let Sum = (...numbers) => {
return numbers.reduce((prev, current) => prev + current );
}
console.log(Sum(1, 2, 3, 4, 5, 6, 7, 8, 9));//45

JSX 에서 다른 방식으로 소품정의하는 것입니다!

...ES6에서 배열 및 객체 연산자를 사용 하고 있습니다 (객체 1은 아직 완전히 지원되지 않음). 기본적으로 이미 소품을 정의한 경우 이러한 방식으로 요소에 전달할 수 있습니다.

따라서 귀하의 경우 코드는 다음과 같습니다.

function yourA() {
  const props = {name='Alireza', age='35'};
  <Modal {...props} title='Modal heading' animation={false} />
}

이제 정의한 소품을 분리하여 필요한 경우 재사용 할 수 있습니다.

다음과 같습니다.

function yourA() {
  <Modal name='Alireza' age='35' title='Modal heading' animation={false} />
}

다음은 JSX의 스프레드 연산자에 대한 React 팀의 인용문입니다.

JSX 스프레드 속성 미리 구성 요소에 배치하려는 모든 속성을 알고 있다면 JSX를 사용하기 쉽습니다.

var component = <Component foo={x} bar={y} />;

Props 변경은 나쁘다
설정하려는 속성을 모르는 경우 나중에 개체에 추가하고 싶을 수 있습니다.

var component = <Component />;
component.props.foo = x; // bad
component.props.bar = y; // also bad

이는 나중에까지 올바른 propTypes를 확인하는 데 도움을 줄 수 없음을 의미하므로 안티 패턴입니다. 즉, propTypes 오류가 숨겨진 스택 추적으로 끝납니다.

소품은 불변으로 간주되어야합니다. 소품 객체를 다른 곳에서 변경하면 예기치 않은 결과가 발생할 수 있으므로 이상적으로는이 시점에서 고정 된 객체가됩니다.

스프레드 속성
이제 스프레드 속성 이라는 JSX의 새로운 기능을 사용할 수 있습니다.

var props = {};
    props.foo = x;
    props.bar = y;
    var component = <Component {...props} />;

전달하는 객체의 속성은 구성 요소의 소품에 복사됩니다.

이것을 여러 번 사용하거나 다른 속성과 결합 할 수 있습니다. 사양 순서가 중요합니다. 이후 속성은 이전 속성보다 우선합니다.

var props = { foo: 'default' };
var component = <Component {...props} foo={'override'} />;
console.log(component.props.foo); // 'override'

이상한 ... 표기법은 무엇입니까?
... 연산자 (또는 확산 연산자)는 ES6의 배열에 대해 이미 지원됩니다. Object Rest 및 Spread Properties에 대한 ECMAScript 제안도 있습니다. JSX에서 더 깨끗한 구문을 제공하기 위해 이러한 지원 및 개발 표준을 활용하고 있습니다.


Python 세계에서 온 사람들에게 JSX Spread Attributes는 Unpacking Argument Lists (Python **연산자) 와 동일합니다 .

나는 이것이 JSX 질문이라는 것을 알고 있지만 비유로 작업하면 때때로 더 빨리 얻는 데 도움이됩니다.


...반응로 (확산 연산자)를 사용한다 :

부모에서 자식 구성 요소로 소품을 전달하는 깔끔한 방법을 제공합니다. 예를 들어 부모 구성 요소에 이러한 소품이 있으면

this.props = {
  username: "danM",
  email: "dan@mail.com"
}

다음과 같은 방식으로 어린이에게 전달 될 수 있습니다.

<ChildComponent {...this.props} />

이것과 비슷한

<ChildComponent username={this.props.username} email={this.props.email} />

그러나 훨씬 깨끗합니다.


세 개의 점 ...스프레드 연산자 또는 나머지 매개 변수를 나타냅니다 .

함수 호출에 대한 인수 또는 배열에 대한 요소가 0 개 이상 예상되는 위치에서 배열 표현식이나 문자열 또는 반복 될 수있는 모든 항목을 확장 할 수 있습니다 .

  • 두 배열 병합

var arr1 = [1,2,3];
var arr2 = [4,5,6];

arr1 = [...arr1, ...arr2];
console.log(arr1);  //[1, 2, 3, 4, 5, 6]

  • 어레이 복사 :

var arr = [1, 2, 3];
var arr2 = [...arr];

console.log(arr); //[1, 2, 3]

참고 : 스프레드 구문은 배열을 복사하는 동안 효과적으로 한 수준 깊이가됩니다. 따라서 다음 예제와 같이 다차원 배열을 복사하는 데 적합하지 않을 수 있습니다 (Object.assign () 및 스프레드 구문과 동일 함).

  • 특정 인덱스 (예 : 3)에서 한 배열의 값을 다른 배열에 추가합니다.

var arr1 = [4,5]
var arr2 = [1,2,3,...arr1,6]
console.log(arr2);	// [1, 2, 3, 4, 5, 6]

  • new로 생성자를 호출 할 때 :

var dateFields = [1970, 0, 1];  // 1 Jan 1970
var d = new Date(...dateFields);

console.log(d);

  • 객체 리터럴에서 확산 :

var obj1 = { foo: 'bar', x: 42 };
var obj2 = { foo: 'baz', y: 13 };

var clonedObj = { ...obj1 };
console.log(clonedObj);	//{foo: "bar", x: 42}

var mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj);	//{foo: "baz", x: 42, y: 13}

참고 foo으로 obj1의 속성은 obj2보다가 덮어 쓴 foo특성

  • 무한한 수의 인수를 배열로 나타낼 수있는 나머지 매개 변수 구문으로 :

function sum(...theArgs) {
  return theArgs.reduce((previous, current) => {
    return previous + current;
  });
}

console.log(sum(1, 2, 3));	//6
console.log(sum(1, 2, 3, 4));	//10

참고 : 스프레드 구문 (스프레드 속성의 경우 제외)은 반복 가능한 객체에만 적용 할 수 있습니다. 따라서 다음과 같이하면 오류가 발생합니다.

var obj = {'key1': 'value1'};
var array = [...obj]; // TypeError: obj is not iterable

참조 1

참조 2


세 개의 점 (...)을 스프레드 연산자라고하며, 이는 개념적으로 ES6 배열 스프레드 연산자와 유사합니다. JSX는 JSX에서 더 깨끗한 구문을 제공하기 위해 이러한 지원 및 개발 표준을 활용합니다.

개체 이니셜 라이저의 스프레드 속성은 제공된 개체의 열거 가능한 속성을 새로 만든 개체로 복사합니다.

let n = { x, y, ...z };
n; // { x: 1, y: 2, a: 3, b: 4 }

참고:

1) https://github.com/sebmarkbage/ecmascript-rest-spread#spread-properties

2) https://facebook.github.io/react/docs/jsx-spread.html


요컨대, 세 개의 점 ...은 ES6 (ES2015)의 스프레드 연산자입니다. 스프레드 연산자는 모든 데이터를 가져옵니다.

let a = [1, 2, 3, 4];
let b = [...a, 4, 5, 6];
let c = [7,8,...a];

console.log (b); 결과 제공 [1,2,3,4,5,6]

console.log (c); 결과 제공 [7,8,1,2,3,4]


...의 의미는 코드에서 사용하는 위치에 따라 다릅니다.

  1. 배열 / 객체 확산 / 복사에 사용 - 배열 / 객체 를 복사하고 새 배열 값을 추가하거나 객체에 새 속성을 추가하는 데 도움이됩니다. 이는 선택 사항입니다.

const numbers = [1,2,3];
const newNumbers = [...numbers, 4];
console.log(newNumbers) //prints [1,2,3,4] 

const person = {
 name: 'Max'
};

const newPerson = {...person, age:28};
console.log(newPerson); //prints {name:'Max', age:28}

  1. 함수 인수를 단일 배열로 병합하는 데 사용 -그런 다음 배열 함수를 사용할 수 있습니다.

const filter = (...args) => {
   return args.filter(el => el ===1);
}

console.log(filter(1,2,3)); //prints [1] 


일반적으로 스프레드 연산자라고하며 필요한 곳으로 확장하는 데 사용됩니다.

const SomeStyle = {
   margin:10,
   background:#somehexa
}

스프레드 연산자 Spread 구문 에 대해 더 많이 필요한 곳에서 이것을 사용할 수 있습니다 .


간단한 방법으로 여러 속성을 전달하는 데 사용되는 분산 속성

{... this.props}는 this.props의 속성을 보유하고 있습니다.

아래 소품과 함께 {...} 스프레드 연산자 사용

this.props = 
 { 
    firstName: 'Dan', 
    lastName: 'Abramov', 
    city: 'New York',
    country: 'USA' 
}

{...} 스프레드없이

<Child 
  firstName={this.props.firstName}
  lastName={this.props.lastName}
  city={this.props.city}
  country={this.props.country}

> 

{...} 스프레드 사용

<Child { ...this.props } />

Dan Abramov 's Tweet about Spread operator (Creator of Redux)


It is common practice to pass props around in a React application. In doing this we able to apply state changes to the child component regardless of whether it is Pure or Impure (stateless or stateful). There are times when the best approach, when passing in props, is to pass in singular properties or an entire object of properties. With the support for arrays in ES6 we were given the "..." notation and with this we are now able to achieve passing an entire object to a child.

The typical process of passing props to a child is noted with this syntax:

var component = <Component foo={x} bar={y} />;

This is fine to use when the number of props is minimal but becomes unmanageable when the prop numbers get too much higher. A problem with this method occurs when you do not know the properties needed within a child component and the typical JavaScript method is to simple set those properties and bind to the object later. This causes issues with propType checking and cryptic stack trace errors that are not helpful and cause delays in debugging. The following is an example of this practice, and what not to do:

var component = <Component />;
component.props.foo = x; // bad
component.props.bar = y;

This same result can be achieved but with more appropriate success by doing this:

var props = {};
props.foo = x;
props.bar = y;
var component = Component(props); // Where did my JSX go?

But does not use JSX spread or JSX so to loop this back into the equation we can now do something like this:

var props = {};
props.foo = x;
props.bar = y;
var component = <Component {...props} />;

The properties included in "...props" are foo: x, bar: y. This can be combined with other attributes to override the properties of "...props" using this syntax:

var props = { foo: 'default' };
var component = <Component {...props} foo={'override'} />;
console.log(component.props.foo); // 'override'

In addition we can copy other property objects onto each other or combine them in this manner:

var oldObj = { foo: 'hello', bar: 'world' };
var newObj = { ...oldObj, foo: 'hi' };
console.log(newObj.foo); // 'hi';
console.log(newObj.bar); // 'world';

Or merge two different objects like this (this is not yet available in all react versions):

var ab = { ...a, ...b }; // merge(a, b)

Another way of explaining this, according to Facebook's react/docs site is:

If you already have "props" as an object, and you want to pass it in JSX, you can use "..." as a SPREAD operator to pass the whole props object. The following two examples are equivalent:

function App1() {
  return <Greeting firstName="Ben" lastName="Hector" />;
}



function App2() {
  const props = {firstName: 'Ben', lastName: 'Hector'};
  return <Greeting {...props} />;
}

Spread attributes can be useful when you are building generic containers. However, they can also make your code messy by making it easy to pass a lot of irrelevant props to components that don't care about them. This syntax should be used sparingly.


Its called spread operator. For eg let hello={name: '',msg:''} let hello1={...hello} Now hello object properties is copied to hello1.


This is a new feature in ES6/Harmony. It is called the Spread Operator. It lets you either separate the constituent parts of an array/object, or take multiple items/parameters and glue them together. Here is an example:

let array = [1,2,3]
let array2 = [...array]
// array2 is now filled with the items from array

And with an object/keys:

// lets pass an object as props to a react component
let myParameters = {myKey: 5, myOtherKey: 7}
let component = <MyComponent {...myParameters}/>
// this is equal to <MyComponent myKey=5 myOtherKey=7 />

What's really cool is you can use it to mean "the rest of the values".

const myFunc = (value1, value2, ...values) {
    // Some code
}

myFunc(1, 2, 3, 4, 5)
// when myFunc is called, the rest of the variables are placed into the "values" array

It is called spreads syntax in javascript.

It use for destructuring an array or object in javascript.

example:

const objA = { a: 1, b: 2, c: 3 }
const objB = { ...objA, d: 1 }
/* result of objB will be { a: 1, b: 2, c: 3, d: 1 } */
console.log(objB)

const objC = { ....objA, a: 3 }
/* result of objC will be { a: 3, b: 2, c: 3, d: 1 } */
console.log(objC)

You can do it same result with Object.assign() function in javascript.

Reference:Spread syntax


Those are called spreads. Just as the name implies. It means it's putting whatever the value of it in those array or objects.

Such as :

let a = [1, 2, 3];
let b = [...a, 4, 5, 6];
console.log(b);
> [1, 2, 3, 4, 5, 6]

참고URL : https://stackoverflow.com/questions/31048953/what-do-these-three-dots-in-react-do

반응형