본문 바로가기
web

vue.js vs react.js

by java개발자 2020. 6. 24.

angular.js, vue.js에 익숙한 front-end 개발자가

react.js를 배우는 과정.


vue.js와 큰 차이점

  • JSX: 이질감 극복하기
    • 예전에 jsp할 때, Scriptlet이란 것이 있었는데, 너무 가독성이 안좋아서 JSTL이 생겨났는데, JSX도 가독성이 나중에는 해결되겠지?
      • jsp 참고
        • Scriptlet: <% %>
        • JSTL: <c:if test=""></c:if>
  • 파일 1개 안에 html, js, style을 쓸 수 없다.
    • 다른 라이브러리를 사용해서 가능하지만, 형태는 JSX만큼 이질감이 크다. (styled-components)
  • Component를 작성하는 방식이 class, function 두가지 방식이 있는데, 서로 사용법이 다르다. React에서는 function 사용을 권장하고 있는데, 처음 배우는 입장에서 기본 기능들은 class 방식에 많이 있기 때문에, function을 할려면 심화 내용을 추가로 익혀야 한다.  처음 배우는 입장에서는 이런 것도 약간 혼란스럽다....
  • array의 배열요소가 변경될때 사용해야 할 array function이 다르다
    • vue.js: 원본 array를 수정하든, 새로 할당하든 상관없다.
      • item 추가일 때, 원본 array에 push 사용 가능
    • react.js: 원본 array에 변경을 할 수 없고, 새로운 array를 할당해야 한다.
      • map, concat, slice, spread 등을 이용해서 새로운 array를 만들어야 한다.
      • item 추가일 때, 사본 array에 push하고, 원본으로 교체

자주쓰던 vue.js의 기능을 react.js에서 찾아보기

this.data

this.state가 있다.

computed, watch

// computed, watch를 state변경으로 구현가능할까?
// vue.js와 react.js의 data(state) 변경 프로세스가 반대인 것 같다.

가공된 A를 사용하고 싶다면,

vue.js: A <- B <- C
A를 먼저 생각하고, A를 만들기 위해 필요한 B, C를 코드상에 포함시켜 놓으면,
vue.js가 자동으로 B,C의 변경사항을 체크해서 B, C가 변경될 때마다 가공된 A를 반환한다.(computed)
(마치 마법과 같이...)

react.js: C -> B -> A
(API response or event) ==> setC -> setB -> setA 방식으로 작동한다.



/**
 * computed
 */
특정 state값들이 변경되면 함수를 실행해서 새로운 변수를 return 한다.
const avg = React.useMemo(() => getAA(), [msg, result]);

/**
 * watch
 */
특정 state변수가 변경되면, 함수를 실행한다.
React.useMemo(() => console.log('A'), [msg]);

methods

// methods는 동일하다

v-if, v-else-if, v-else

// JSX에서 처리

  return (
    <div>
      {name === 'aaa' 
      ? <h1>aaa</h1> 
      : (
        name === 'bbb'
        ? <h1>bbb</h1> 
        : <h1>ccc</h1>
      )}
      {html}
    </div>
   )
// script로 처리

  let html;
  if (name === 'aaa') {
    html = <h1>aaa</h1>;
  } else if (name === 'bbb') {
    html = <h1>bbb</h1>;
  } else {
    html = <h1>ccc</h1>;
  }
  
  return (
    <div>
      {html}
    </div>
  );
pug를 이용하면, if, else if, else 가 가능하다.
// https://github.com/pugjs/babel-plugin-transform-react-pug

v-show

//

v-for

JSX를 이용해야 한다.

const Test = () => {
  const list = ['a', 'b', 'c', 'd'];
  return (
    <div>
      <ul>
        {
          list.map((val, idx) => 
            <li key={idx}>{val}</li>
          )
        }
      </ul>
    </div>
  );
};
const Test = () => {
  const list = ['a', 'b', 'c', 'd'];
  const html = list.map((val, idx) => <li key={idx}>{val}</li>);
  return (
    <div>
      <ul>
        {html}
      </ul>
    </div>
  );
};

v-html

//

ref

<input type="text" ref={this.input} />

v-model

 

v-model의 기능은 <input>, <select> 태그 등의 value값을 양방향(script <-> UI 수정)으로 동기화되는 편한 기능인데, react.js에는 한번에 할 수 있는 기능이 없다.

대안1: value와 onChange로 지정해야 한다. (제어컴포넌트라고 부른다.)

<input type="text" value={this.state.value} onChange={this.handleChange} />

 

대안2: ref를 이용한다. (비제어 컴포넌트라고 부른다.)

https://ko.reactjs.org/docs/uncontrolled-components.html

<input type="text" ref={this.input} />

스타일: css의 class, style,  scoped, /deep/

//

component, props, slot, $emit

//

extend, mixin

//

라이프사이클: created, mounted, updated, destroyed

//

this.$nextTick()

this.$forceUpdate()

//

router

//

Vuex

//

 


react.js의 class 방식과 function 방식의 차이

  class function
state state = {number: 0};

this.setState({number: 1});
const [number, setNumber] = React.useState(0);

setNumber(1);
     
     
     
라이프사이클 componentDidMount, componentDidUpdate React.useEffect
    React.useReducer
    React.useMemo
React.useCallback
  shouldComponentUpdate React.memo
ref this.ref React.useRef
     
     

 


vue.js, react.js 공통 질문

리스트 내에서 순서가 변경되었을 때, animation 같은 것은 어떻게 처리하나?

리스트를 다시 렌더링할 수는 있지만, 옮겨지는 모습까지 애니메이션을 줄 수 있을까?

'web' 카테고리의 다른 글

github actions  (0) 2021.04.27
graphql 기본 문법 정리  (0) 2020.07.03
react.js  (0) 2020.07.03
[spring을 spring 답게] spring 세팅  (0) 2020.03.27
Vue.js global error 처리  (0) 2020.03.13