HTTP 웹/React

React - 생활코딩(12) - Create의 Form 기능 / rendering 제어

코르시카 2021. 5. 13. 00:30

■ Create에 Form 추가

1) form 태그 생성 + 하위에 input - submit type 추가

> 위와 같은 구성으로 form 태그 안의 내용을 원래는 서버 등에 보낼 수 있음

> 서버의 주소는 form tag attribute에 넣으면 됨

   action = "server location",  method = "get / post" (post URL에서 보내는 값 노출 안됨)

   onSubmit = "callback for submit from input tag" ( form태그 하위 input-submit 클릭시 호출되는 콜백 )

 

2) App.js에서 props로 하위 component 값 받아오고 업데이트

> new object를 list에 추가해줌

> 기본 JS method 사용( push )

 

 

■ Rendering 제어

매번 불필요한 rerendering을 막으려면

component 안에 shoudlComponentUpdate 매써드를 선언하고

newProps, newState 외 기타 로직으로 통해

return true / false로 reload 제어

> shoudlComponentUpdate 는 render 이전에 불림

※ return 에 따라

true : component안의 render 메써드가 매번 새로 업데이트 됨 ( state 바뀔 때 마다)
false : component안의 render 메써드가 불리지 않아 업데이트 안되고 최초 한번시만 rendering 시 업데이트

 

※ new objects

newProps : Props 중에 새로운 값 받음

this.props. XX for previous : 이전 값을 볼 수 있음

 

그대로인 1번
바뀌어버린 2번

> 1번예시에서는 update 하지 않고, 2번에서는 업데이트 해야 할 때 밑에처럼 구성 가능

    shouldComponentUpdate(nextProps, nextState){
        return (JSON.stringify(nextProps) != JSON.stringify(this.props));
    }

 

※ shoudlComponentUpdate의 old new 비교시 유의점

밑에처럼 코드를 구성하면, 새로운 데이터를 추가시 mutable하기 때문에 

this.props .XXX 와 newProps.data가 같은 곳을 바라보도록 되어서 old new 비교가 되지 않음

        <CreateContent 
          title={_title} desc={_desc} 
          onEventTake = {function(newTitle, newDesc){
            // add new content
            let new_object = {
              id:this.state.contents.length+1,
              title:newTitle,
              desc:newDesc
            }
            let tmp_state_contents = this.state.contents
            tmp_state_contents.push(new_object);

            this.setState({contents:tmp_state_contents});
          }.bind(this)}
        >
        </CreateContent>

아래와 같이 고쳐서

원본을 가지는 부분과 새로운 부분으로 나누어서 업데이트 하면 됨

( concat는 return 된 array와 원본 array가 다른 메모리에 위치해있기 때문 )

> this.props는 render 다시 불리기 전에는 이전의 원본 array를 보고 있는 셈

            // let tmp_state_contents = this.state.contents
            // tmp_state_contents.push(new_object);
            
            // .. 를 다음으로 바꿈! ...
            
            let tmp_state_contents = this.state.contents.concat(new_object);
            this.setState({contents:tmp_state_contents});

 

 

■ state의 원본

state에 대한 변경을 할때는 원본을 보존하는 것이 좋음

큰 규모의 프로그램으로 넘어가게 되면서 성능 최적화가 필요해지면

shouldComponentUpdate가 필요해지는데 이때 원본을 보전해야할 필요성이 있으므로!

 

 

■ 다른 array method

> Array.from( ... )  을 사용하면 완전 복제 됨

b가 array from 메써드로 a에서 copy된 array일 때

a === b 는 false 처리

// 1. Array.from 메써드 사용(완전 복제)
let tmp_state_contetns = Array.from(this.state.contents);
tmp_state_contetns.push(new_object);
this.setState({contetns:tmp_state_contetns});


// 2. concat를 쓰는 경우
// let tmp_state_contents = this.state.contents.concat(new_object);
// this.setState({contents:tmp_state_contents});

 

※ Array가 아니고 Object인 경우

Object.assign( ... ) 메써드 사용

 

※ 위의 immutable / mutable 혼란을 막고자

immutable.js 라이브러리도 존재하여, 모든 리턴값/ 작업을 원본이 아닌 copy를 가져오는 라이브러리도 존재

https://immutable-js.github.io/immutable-js/

 

Immutable.js

Immutable collections for JavaScript Immutable data cannot be changed once created, leading to much simpler application development, no defensive copying, and enabling advanced memoization and change detection techniques with simple logic. Persistent data

immutable-js.github.io


■ vscode React 설정

penguingoon.tistory.com/262

 

VSCODE 리액트 자동완성 기능 설정하기 (feat. user snippets)

안녕하세요! 이번 포스팅에서는 Visual Studio Code(이하 VSCODE)에서 리액트 앱을 개발할 때 무척 유용한 기능인 리액트 컴포넌트 기본 템플릿 자동완성 기능을 추가하는 방법에 대해 안내하도록 하겠

penguingoon.tistory.com

 

 


참조 :

www.youtube.com/watch?v=YJk9PgYnFmI&list=PLuHgQVnccGMCRv6f8H9K5Xwsdyg4sFSdi&index=31

www.youtube.com/watch?v=y5FAg6bJmwE&list=PLuHgQVnccGMCRv6f8H9K5Xwsdyg4sFSdi&index=32

www.youtube.com/watch?v=SLb4p9T-yZA&list=PLuHgQVnccGMCRv6f8H9K5Xwsdyg4sFSdi&index=34

www.youtube.com/watch?v=OpLMcB1nRkE&list=PLuHgQVnccGMCRv6f8H9K5Xwsdyg4sFSdi&index=33

https://www.youtube.com/watch?v=SkTUocMjXTg&list=PLuHgQVnccGMCRv6f8H9K5Xwsdyg4sFSdi&index=35

 

반응형