TIL 0217

Kimaramy·2020년 2월 17일
0

Today I Learned

목록 보기
1/5

maxLength={4} 또는 max={9999}

버그

<input type="number" maxLength={4}>

디버깅

<input type="text" maxLength={4}>

또는

<input type="number" max={9999}>

input의 type="number"이면 입력되는 값이 숫자이므로 maxLength는 올바른 property가 아니다. type="number"이면 max={9999}를 주어 자리수를 4자리까지 제한할 수 있다.

하지만 나는 애초에 길이가 4자리를 초과해 작성되게 하지 않기 위함이었음으로 type="text"로 변경해 입력되는 값이 문자열이 되게했다. 그래서 maxLength={4}("4"로 해도 된다) 그대로 하고, onSubmitForm 함수 내부에서 parseInt(value) 했을때 NaN이 반환된다면 오류로 처리하도록 했다.


리액트 오버 렌더링 방지를 통해 성능 향상하기

setState()는 값의 변경에 상관없이 render() 함수를 실행시킨다.
state의 값이 변경되지 않음에도 렌더가 되는 문제가 발생할 수 있는데, 다음 방법들을 사용해 방지할 수 있다. (props의 비의도적인 렌더 오류도 방지 가능)

1. shouldComponentUpdate

import React, { Component } from 'react'; 

export default class Tries extends Component {
  shouldComponentUpdate(nextProps, nextState, nextContext) {
  	if (this.props.tryInfo.try !== nextProps.tryInfo.try) {
      return true;
    }
  	return false;
  }
  render() {
    console.log('Try 컴포넌트가 렌더링 되었습니다.');
    return (
      <li>
        <div>시도: {tryInfo.try}</div>
        <div>결과: {tryInfo.result}</div>
      </li>
    );
  };
};

참고 : shouldComponentUpdate() | React API

2. Component 대신 PureComponent

import React, { PureComponent } from 'react'; 

export default class Tries extends PureComponent {
  render() {
    console.log('Try 컴포넌트가 렌더링 되었습니다.');
    return (
      <li>
        <div>시도: {tryInfo.try}</div>
        <div>결과: {tryInfo.result}</div>
      </li>
    );
  };
};

3. React.memo - only for updating props

import React from 'react'; 

export const Tries = ({tryInfo}) => {
  console.log('Try 컴포넌트가 렌더링되었습니다.');
  return (
    <li>
      <div>시도: {tryInfo.try}</div>
      <div>결과: {tryInfo.result}</div>
    </li>
  );
};

const MemorizedTries = React.memo(Tries);
export default MemorizedTries;

또는

import React from 'react'; 

const Tries = React.memo(({tryInfo}) => {
  console.log('Try 컴포넌트가 렌더링되었습니다.');
  return (
    <li>
      <div>시도: {tryInfo.try}</div>
      <div>결과: {tryInfo.result}</div>
    </li>
  );
});

export default Tries; 

참고 : React.memo | React API

더 알아보기


profile
스타트업에서 Software Engineer로 일하고 있습니다

0개의 댓글