관리 메뉴

Silver Library (Archived)

React.js - summary note 본문

카테고리 없음

React.js - summary note

Chesed Kim 2021. 5. 6. 16:03
반응형

1.0 시작.

JavaScript를 다시 보고 싶다면 이 가이드를 추천합니다. JavaScript의 최신 버전인 ES6의 몇 가지 기능을 사용한다는 사실에 주목해주세요. 자습서에서는 화살표 함수, 클래스, let, const를 사용합니다. Babel REPL을 사용하여 ES6 코드가 어떻게 컴파일되는지 확인할 수 있습니다.

ko.reactjs.org/tutorial/tutorial.html

 

자습서: React 시작하기 – React

A JavaScript library for building user interfaces

ko.reactjs.org

Advisory:

Patient. Don't overthink too much. Start input something first.

 

If I come whiteout in my thoughts, see:

https://www.taniarascia.com/understanding-objects-in-javascript/https://www.w3schools.com/js/js_objects.asp

 

An easy way to remember the difference between object properties and methods is to think of a property as a noun, and a method as a verb. name, race and weapon are all nouns associated with an object, and are properties. fight() or talk() are verbs that might be used as a method function definition.

 

1.1 To think as React.js developer

ko.reactjs.org/docs/thinking-in-react.html

 

1.2 F&Q (recommended)

ko.reactjs.org/docs/faq-state.html#what-is-the-difference-between-state-and-props

 

컴포넌트 State – React

A JavaScript library for building user interfaces

ko.reactjs.org

1.3 Key features

  • arrow functions
  • Template literals
  • Object destructuring
  • Spread operator
  • classes
  • Array map, Array filter
  • forEach (which includes) Push

1.4 Key note

What is state?

React has another special built-in object called state, which allows components to create and manage their own data. So unlike props, components cannot pass data with state, but they can create and manage it internally.

 

What is useState?

https://blog.logrocket.com/a-guide-to-usestate-in-react-ecb9952e406c/

useState is a hook that is one of npm open sources I can use it in my project.

 

So, when should I use state and useState? (Conclusion)

https://www.freecodecamp.org/news/react-js-for-beginners-props-state-explained/

 

What is Props?

A simple word:

wherever function or variable , elsewhere I include props, then that one is ready to deliver that information as of its function or variable name.

https://www.freecodecamp.org/news/react-js-for-beginners-props-state-explained/

 

Props is a sort of bridge that allows file to another file, which needs to imply the departing side's content on the current one. 

https://itnext.io/what-is-props-and-how-to-use-it-in-react-da307f500da0

For example, the File A component can be implied on File B as a form of (props). It acts like a bridge. ★Caution: in programming of react.js, it looks like they express this as: 'pass data.' Better remember this way.

https://www.youtube.com/watch?v=KvapOdsFK5A&t=93s 

//parentComponent.jsx

class ParentComponent extends Component {
	render() {
    	return (
        	<div>
            	<h1>I'm the parent component
                <h3><ChildComponent text="I'm the 1st child"/></h3>
                <h3><ChildComponent text="I'm the 2nd child"/></h3>
                <h3><ChildComponent text="I'm the 3rd child"/></h3>
             </div>
          );
     }
 }
 
 export default ParentComponent;
 
 ###########################################
 What this mean...?
 
 function addition(arg1, arg2){
 	return arg1 + arg2;
 }
 
 const Component = (props) => {
 	// rules
 }
 #############################################
 //childComponent.jsx
 
 const ChildComponent = (props) => {
 	return (<p>I'm the 1st child</p>);
 };
 
 export default ChildComponent;

In other words...

class ParentComponent extends Component {    
    render() {    
        return (        
            <ChildComponent name="First Child" />    
        );  
    }
}

const ChildComponent = (props) => {    
    return <p>{props.name}</p>; 
};

So, what is state? And how I use it?

React has another special built-in object called state, which allows components to create and manage their own data. So unlike props, components cannot pass data with state, but they can create and manage it internally.

 

※ See how 'state' are applied here.

class Test extends React.Component {    
    constructor() {    
        this.state = {      
            id: 1,      
            name: "test"    
        };  
    }    
    
    render() {    
        return (      
            <div>        
              <p>{this.state.id}</p>        
              <p>{this.state.name}</p>      
            </div>    
        );  
    }
}

Remember, once class is claimed - constructor must follows. Then 'this' indicates class 'Test'.

this.state =

such form literally express what is in that state component.

Remember! state will be managed IN THE COMPONENT. IN! IN! IN! Be sure to review the above codebox. where this.state belongs to? Correct. React.Component 

 

1.2.1 props and state?

props (“properties”의 줄임말) 와 state 는 일반 JavaScript 객체입니다. 두 객체 모두 렌더링 결과물에 영향을 주는 정보를 갖고 있는데, 한 가지 중요한 방식에서 차이가 있습니다. props는 (함수 매개변수처럼) 컴포넌트 전달되는 반면 state는 (함수 내에 선언된 변수처럼) 컴포넌트 안에서 관리됩니다.

 

1.3 Arrow function?

Remember, Arrow function contains function. So, it is based for the function.

(minimise the code of expressing 'function to return', by expressing it as follows:

// initial code (before applying arrow function)
function sayHello(name) {
	return "Hello " + name;
}

// this is how arrow function applied (come from the above function sayHello)
const sayHello = (name = "Human") => "Hello " + human;
##########################################
const kim = sayHello();

console.log(kim);

Look at this:

const App = () => {
	const sayHello = () => console.log("hello");
    useEffect(() => {
    	sayHello();
    });
    
//see line no.2. That's the evidence how 'arrow function' works.

Bonus. API? Yes, they were DOM API.

 

The following is a brief list of common APIs in web and XML page scripting using the DOM.

 

 

2.0 React.

2.1 내가 내린 한 줄 정의

React.js -> JS

기존의 JavaScript 는 너무 길고, 외워야 할 게 많은 번거로운 손 아픈 문법 코드가 많음. 초보자에게 쉽진 않음. React.js 의 경우, 이를 간소화 해서 JS 로 문법을 변환 해서 표시해주는 JS framework. 특히 특정 부분만 건드려서 자료를 업데이트 및 추가하는 것에 특화된데다, 입문자도 접하기 쉬운 점에서 희망이 큼.

 

2.1.1 습득을 위한 필수 이해 요소?

props 와 component 등, 반드시 이를 다루는 small scale project 를 한번 쯤은 만들어 봐야 함.

 

2.2 CSS 는 extra 요소.

주로 CSS 는 복붙 수준으로 가져다가 쓰는 것을 부끄러워 하지 않아도 됨. 사실상 모든 곳이 그런 식임. 모든 코드의 핵심은 왜 그걸 가져다 쓰고, 그걸 잘 연결 해 내느냐임. 이해하고 하기만 하면 문제 없음.

 

2.3 React.js 문법

모든 내용은 자습서: React 시작하기 - React (아래 최하단부 링크) 공식 문서를 따름.

 

2.3.1 Props 를 통해 데이터 전달하기 - 1번

class Square extends React.Component {
 render() {
   return (
     <button className="square" onClick={() => alert('click')}>
       {this.props.value}
     </button>
   );
 }
}

onClick={() => alert('click')}이 어떻게 동작하는지 살펴보면 onClick prop으로 함수를 전달하고 있습니다. React는 클릭했을 때에만 이 함수를 호출할 것입니다. () =>을 잊어버리고 onClick={alert('click')}이라고 작성하는 것은 자주 발생하는 실수이며 컴포넌트가 다시 렌더링할 때마다 경고 창을 띄울 것입니다.

 

노트: prop 은 property(속성).

결국, onClick={() => alert('click')} 에서,

onClick={(이 공간이)

일종의 prop 이라고 생각하는게 맞음.

 

2.3.2 사용자와 상호작용하는 컴포넌트 만들기 - 2번

참고: 여기서 화살표 함수의 사용 예시가 등장.

 

"무언가를 '기억하기' 위해 component 는 state 를 사용합니다."

 

주의

JavaScript 클래스에서 하위 클래스의 생성자를 정의할 때 항상 super를 호출해야합니다. 모든 React 컴포넌트 클래스는 생성자를 가질 때 super(props) 호출 구문부터 작성해야 합니다.

*추신: 생성자란? [React] constructor() 생성자 사용법

 

class Square extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: null,
    };
  }

  render() {
    return (
      <button
        className="square"
        onClick={() => this.setState({value: 'X'})}
      >
        {this.state.value}
      </button>
    );
  }
}

 

Square render 함수 내부에서 onClick 핸들러를 통해 this.setState를 호출하는 것으로 React에게 <button>을 클릭할 때 Square가 다시 렌더링해야 한다고 알릴 수 있습니다.

업데이트 이후에 Square의 this.state.value 'X'가 되어 게임 판에서 X가 나타나는 것을 확인할 수 있습니다. 어떤 Square를 클릭하던 X가 나타날 것입니다.

 

컴포넌트에서 setState를 호출하면 React는 자동으로 컴포넌트 내부의 자식 컴포넌트 역시 업데이트합니다.

 

★2.3.3 State 끌어올리기

각 Square에 숫자를 넘겨주었을 때와 같이 Board 컴포넌트는 각 Square에게 prop을 전달하는 것으로 무엇을 표시할 지 알려줍니다.

 

여러개의 자식으로부터 데이터를 모으거나 두 개의 자식 컴포넌트들이 서로 통신하게 하려면 부모 컴포넌트에 공유 state를 정의해야 합니다. 부모 컴포넌트는 props를 사용하여 자식 컴포넌트에 state를 다시 전달할 수 있습니다. 이것은 자식 컴포넌트들이 서로 또는 부모 컴포넌트와 동기화 하도록 만듭니다.

 

state를 부모 컴포넌트로 끌어올리는 것은 React 컴포넌트를 리팩토링할 때 흔히 사용합니다.

 

class Square extends React.Component {
  render() {
    return (
      <button
        className="square"
        onClick={() => this.props.onClick()}
      >
        {this.props.value}
      </button>
    );
  }
}

 

★중요

Square를 클릭하면 Board에서 넘겨받은 onClick 함수가 호출됩니다. 이 때 일어나는 일을 정리해보겠습니다.

  1. 내장된 DOM <button> 컴포넌트에 있는 onClick prop은 React에게 클릭 이벤트 리스너를 설정하라고 알려줍니다.
  2. 버튼을 클릭하면 React는 Square의 render() 함수에 정의된 onClick 이벤트 핸들러를 호출합니다.
  3. 이벤트 핸들러는 this.props.onClick()를 호출합니다. Square의 onClick prop은 Board에서 정의되었습니다.
  4. Board에서 Square로 onClick={() => this.handleClick(i)}를 전달했기 때문에 Square를 클릭하면 this.handleClick(i)를 호출합니다.
  5. 아직 handleClick()를 정의하지 않았기 때문에 코드가 깨질 것입니다. 지금은 사각형을 클릭하면 “this.handleClick is not a function”과 같은 내용을 표시하는 붉은 에러 화면을 보게됩니다.

 

주의

DOM <button> 엘리먼트의 onClick 어트리뷰트는 내장된 컴포넌트라는 점에서 React에게 특별한 의미가 있습니다. Square같은 사용자 정의 컴포넌트의 경우 이름 지정은 자유롭습니다. Square의 onClick prop이나 Board의 handleClick 함수에는 어떤 이름도 붙일 수 있으며 코드는 동일하게 작동합니다. React에서 이벤트를 나타내는 prop에는 on[Event], 이벤트를 처리하는 함수에는 handle[Event]를 사용하는 것이 일반적입니다.

 

// 이 class Board 에서 나온 this.state 란, Board 를 가리킴.
class Board extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      squares: Array(9).fill(null),
    };
  }
    
// 여기에서 나온 this.setState 란, 여전히 Board 를 가리킴. 
//즉, 위의 this.state 가 있는 Board (블럭을)를 가리킴.

  handleClick(i) {
    const squares = this.state.squares.slice();
    squares[i] = 'X';
    this.setState({squares: squares});
  }

이 코드블럭에서 나온 this 는, 명백하게 Board 를 가리킴.

 

Square 컴포넌트가 더 이상 state를 유지하지 않기 때문에 Square 컴포넌트는 Board 컴포넌트에서 값을 받아 클릭될 때 Board 컴포넌트로 정보를 전달합니다. React 용어로 Square 컴포넌트는 이제 제어되는 컴포넌트입니다. Board는 이들을 완전히 제어합니다.

 

2.3.4 불변성이 왜 중요할까요?

... 특정 행동을 취소하고 다시 실행하는 기능은 애플리케이션에서 일반적인 요구사항 입니다. 직접적인 데이터 변이를 피하는 것은 이전 버전의 게임 이력을 유지하고 나중에 재사용할 수 있게 만듭니다.

 

2.3.4.1 변화를 감지함.

객체가 직접적으로 수정되기 때문에 복제가 가능한 객체에서 변화를 감지하는 것은 어렵습니다. 감지는 복제가 가능한 객체를 이전 사본과 비교하고 전체 객체 트리를 돌아야 합니다.

불변 객체에서 변화를 감지하는 것은 상당히 쉽습니다. 참조하고 있는 불변 객체가 이전 객체와 다르다면 객체는 변한 것입니다.

 

2.3.4.1 React 에서 다시 렌더링하는 시기를 결정함.

불변성의 가장 큰 장점은 React에서 순수 컴포넌트를 만드는 데 도움을 준다는 것입니다. 변하지 않는 데이터는 변경이 이루어졌는지 쉽게 판단할 수 있으며 이를 바탕으로 컴포넌트가 다시 렌더링할지를 결정할 수 있습니다.

 

2.3.5 함수 컴포넌트 (★★★★★)

가장 많이 헷깔릴 수 밖에 없었던 곳 #1.

 

React에서 함수 컴포넌트는 더 간단하게 컴포넌트를 작성하는 방법이며 state 없이 render 함수만을 가집니다. React.Component를 확장하는 클래스를 정의하는 대신 props를 입력받아서 렌더링할 대상을 반환하는 함수를 작성할 수 있습니다. 함수 컴포넌트는 클래스로 작성하는 것보다 빠르게 작성할 수 있으며 많은 컴포넌트를 함수 컴포넌트로 표현할 수 있습니다.

 

2.3.6 순서 만들기

Board 블록 안의 this.state 는, 초기 state 의 설정을 의미함.

이 초기 state를 기점으로 향후 setState 로 특정 행동(명령)을 입력 시, 이 state 를 기점으로 업데이트가 이뤄 질 것.

class Board extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      squares: Array(9).fill(null),
      xIsNext: true,
    };
  }

  handleClick(i) {
    const squares = this.state.squares.slice();
    squares[i] = this.state.xIsNext ? 'X' : 'O';
    this.setState({
      squares: squares,
      xIsNext: !this.state.xIsNext,
    });
  }

  renderSquare(i) {
    return (
      <Square
        value={this.state.squares[i]}
        onClick={() => this.handleClick(i)}
      />
    );
  }

  render() {
    const status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');

    return (
      <div>
        <div className="status">{status}</div>
        <div className="board-row">
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
        </div>
        <div className="board-row">
          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}
        </div>
        <div className="board-row">
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
        </div>
      </div>
    );
  }
}

핵심은 render() 에 나오는 (this.state.xIsNext ? 'X' : 'O');  부분. 명백하게 this 는 Board 를 가리키고 있다.

이는 아래의 return 블럭의 {this.renderSquare(0)} 에서도 Board 를 가리킴을 확연히 의미!

 

2.3.7 다시 state 끌어올리기 (★★)

가장 많이 헷깔릴 수 밖에 없었던 곳 #2.

A 컴포넌트에서 B 컴포넌트로 특정 컴포넌트 내용, 그리고 (onClick) props 를 전달하는 것.

 

다음으로 Game 컴포넌트에서 Board 컴포넌트로 squares onClick props를 전달하겠습니다. Board에서 여러 개의 Square에 쓰일 단일 클릭 핸들러를 가졌기 때문에 각 Square의 위치를 onClick 핸들러에게 넘겨주어 어떤 Square를 클릭했는지 표시할 것입니다. Board 컴포넌트를 변경하는 순서는 아래와 같습니다.

// 전형적인 numeric 반복문
class Board extends React.Component {
  renderSquare(i) {
    return (
      <Square
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
      />
    );
  }

  render() {
    return (
      <div>
        <div className="board-row">
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
        </div>
        <div className="board-row">
          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}
        </div>
        <div className="board-row">
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
        </div>
      </div>
    );
  }
}

 

2.3.8 과거 mapping 부분 map()

 

앞에서 React 엘리먼트는 애플리케이션에 전달할 수 있는 클래스형 JavaScript 객체라는 것을 배웠습니다. React 엘리먼트 배열을 사용하면 여러 아이템을 렌더링할 수 있습니다.

JavaScript에서 배열은 데이터를 다른 데이터와 함께 매핑할 때 사용하는 map() 함수를 가지고 있습니다. 이 함수는 아래와 같이 사용할 수 있습니다.

 

map() 함수는 정말 그 mapping 의 의미가 맞음.

 

 

 


3.0 현재 확실하게 로직을 이해하는 것. (Need update for this section)

유형 1. class x extends component | ko.reactjs.org/tutorial/tutorial.html

class ShoppingList extends React.Component {
  render() {
    return (
      <div className="shopping-list">
        <h1>Shopping List for {this.props.name}</h1>
        <ul>
          <li>Instagram</li>
          <li>WhatsApp</li>
          <li>Oculus</li>
        </ul>
      </div>
    );
  }
}

 

4.0 현재 다소 불안정한 부분

- state 끌어올리기

- 다시 state 끌어올리기

 

4.1 How to review all the stuff again?

See the difference from step by step, in reversal.

Or see this

 

5.0 Self-check

5.1 in some case, 

# what I know

export default something;

# What I saw sometimes
export default () => ...

This type of export form exists to reduce the code length.

 

6.0 Can I explain the following elements?

www.interviewbit.com/react-interview-questions/