Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

리액트 정리

[React] 웹게임 기타 알고있을 것 본문

리액트/웹게임

[React] 웹게임 기타 알고있을 것

버그킴 2020. 1. 31. 15:10

setState는 render(){}안에 쓰는것 아니다.

왜? 렌더가 실행되면 this.setState가 실행되고, this.setState가 실행되면 렌더가 실행되고..

무한반복 -> 브라우저에 문제를 발생시킴. 


부모로부터 받은 props를 자식이 바꾸고 싶을 때

자식은 props를 바꾸지 않는다. 자식이 바꿔버리면 부모가 뜻하지 않게 바뀌어버림 -> 문제가 됨.

진짜 바꾸고 싶으면, state로 만든다음에 state를 바꾼다

 

Hooks

import React, { memo, useState } from "react";

const Try = memo(({tryInfo}) => {
  // tryInfo.try = 'hello'; // 이러면 안돼요
  const [result, setResult] = useState(tryInfo.result) // 돼요
  const onClick = () => {
    setResult('1');
  };
  return (
    <li>
      <div>{tryInfo.try} </div>
      <div onClick={onClick}>{tryInfo.result} </div>
    </li>
  )
})

export default Try;

 

Class

import React, { PureComponent } from 'react'
class Try extends PureComponent {
  constructor(props) {
    super(props)
    // 다른 정밀한 동작. 기본 객체로 안될 때
    const filtered = this.props.filter(() => {
      
    });
    this.state = {
       result: filtered,
       try: this.props.try,
    }
  }

  render() {
    const {tryInfo} = this.props;
    return (
      <li>
        <div>{tryInfo.try} </div>
        <div>{tryInfo.result} </div>
      </li>
    );
  }
}