Skip to content

React에서 중요할 수 도 있는 이모저모

dkfma4915 edited this page Dec 16, 2020 · 8 revisions
  • React에서 중요할 수도 있는 이모저모를 기록하는 문서
  • 지속적으로 Update할 예정
  • '추가하면 괜찮겠다' 싶은 것도 추가해주면 압도적 감사!!

이벤트 bind 함수에 관하여

let obj = {name : 'egoing'};

function bindTest() {
  console.log(this.name);
}

bindTest();

위 코드를 실행하면 undefined를 실행한다. bindTest() 함수에는 this가 없기 때문이다(우리는 `egoing'이 나오길 원하고 있다.).

그렇다면 어떻게 해야 될까?

let bindTest2 = bindTest.bind(obj);

bindTest2();

실행하면 제대로 egoing이 나온다.

즉, bind() 함수에 들어간 obj 객체가 bindTest2this 객체가 되는 것이다.

이때 bindTest2bindTest 함수와 내용은 같다.

자세한 것은 여기

이벤트 setState 함수에 관하여

Component는 만들어질때 자동적으로(그리고 우선적으로) constructor(props) 함수를 실행하게 된다(이는 다른 언어들의 웬만한 class와 같다). 즉 객체가 만들어지면 constructor(생성자)가 호출된다.

참고로 Component의 Instance가 생성되어 DOM에 삽입될 때 다음 순서로 호출된다.

  1. constructor()
  2. static getDeriveStateFromProps()
  3. render()
  4. componentDidMount()

이때 보통 state 값을 정해주게 되는데 생성자 호출이후에 event로 인해 state 값을 바꾸려면 보통 이렇게 쓸 수 있다.

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mode:'read',
      subject:{title:'WEB', sub:'world wide web'},
      welcome:{title:'welcome', desc:'hello react'}
    }
  }
  render() {
    <div className = "APP">
      this.state.mode = 'welcome';
    </div>
  }
}

이렇게 되면 this.state.mode값이 변하지 않는다.

따라 다음과 같이 써야된다.

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mode:'read',
      subject:{title:'WEB', sub:'world wide web'},
      welcome:{title:'welcome', desc:'hello react'}
    }
  }
  render() {
    <div className = "APP">
      this.setState({
        mode: 'welcome'
      });
    </div>
  }
}

this.setState 함수로 작성하면 안전하게 변경할 수 있다.

주의사항

react 공식 홈페이지에 따르면 constructor() 내부에서 setState()를 호출하지 말라고 써져있다.주의하자.

Tree식 Component 구조에서

image

  1. props는 부모 컴포넌트가 자식 컴포넌트에게 주는 값. 자식 입장에서는 props를 받기만하고 받아온것을 직접 수정은 불가하다. => read only

  2. state는 컴포넌트 내부에서 선언하고 내부에서 값을 변경할수있다. 부모가 자식(하위 컴포넌트)의 state화 되어있는 값을 변경하고싶을땐 props로 변경한다. 자식이 부모(상위 컴포넌트)의 state화 되어있는 값을 변경하고싶을땐 setState() 라는 함수를 사용(이벤트)

shouldComponentUpdate

class App extends Component {
    shouldComponentUpdate(newProps, newState) {
        console.log(newProps.data);
        if(this.props.data === newProps.data) {
            return false;
        }
        return true;
    }
    render() {

    }
}

위의 shouldComponentUpdate함수의 return값을 true로 쓰면 정상적으로 돌아간다. state 값이 변경 할 때마다 render() 함수를 계속 호출 하기 때문이다.

그러나 return false를 하면 render() 함수가 호출되지 않는다. 따라서 보여지는 것이 변경되지 않는다.

또한 shouldComponentUpdate 함수의 newPropsnewState를 통해 변경된 값에 접근할 수 있다. return 전에 this.props.data로 하면 변경되기 전의 data 값이 나온다.

return() 안에서 주석 처리 시 유의할 점

class Subject extends Component {
  render() {
    return (
      // 안녕
    );
  }
}

보통 주석 처리할 때 사용하는 //을 사용하면 주석이 되지않고 에러가 날 것이다. 그럴때는 !

class Subject extends Component {
  render() {
    return (
      {/* 안녕 */}
    );
  }
}

이렇게 원하는 주석을 / /을 사용하여 쓰고, 이 주석 전체를 {}로 감싸야한다 !!

Reference

Clone this wiki locally