[TIL] React-state

link717ยท2020๋…„ 10์›” 12์ผ
0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
10/53
post-thumbnail

๐Ÿฑ State

state๋Š” render ํ•จ์ˆ˜๊ฐ€ ์‹คํ–‰๋˜๋Š” ์กฐ๊ฑด์œผ๋กœ component์˜ state๋Š” props์™€ ๋‹ค๋ฅด๊ฒŒ ์™ธ๋ถ€๋กœ ์ „๋‹ฌ๋˜์ง€ ์•Š๊ณ  ์ž์‹ ๋งŒ์˜ ๊ณ ์œ ํ•œ state๋ฅผ ๊ฐ–๋Š”๋‹ค.
โŽ class ์•ˆ์— state๋ฅผ ์ถ”๊ฐ€ํ•  ๋•Œ๋Š” render()์™€ ๊ตฌ๋ถ„ํ•˜๊ธฐ ์œ„ํ•œ ,๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์•ˆ๋œ๋‹ค. class๋Š” ๊ฐ์ฒด๊ฐ€ ์•„๋‹ˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

  • Class component์— state ์ถ”๊ฐ€ํ•˜๊ธฐ
    โŽ super(props); ์„ ์–ธ์ „์—๋Š” this. syntax๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๋‹ค.

  • State์— ์ ‘๊ทผํ•˜๊ธฐ

    . this.state.name-of-property

๐Ÿญ Update state(this.setState)

state๋Š” ์ž์‹ ์˜ state๋ฅผ ์ฝ๋Š” ๊ฒƒ ๋ฟ๋งŒ ์•„๋‹ˆ๋ผ ์Šค์Šค๋กœ state๋ฅผ ๋ณ€ํ™”์‹œํ‚ฌ ์ˆ˜๋„ ์žˆ๋‹ค. state๋ฅผ ๋ฐ”๊ฟ€ ๋•Œ๋Š” this.setState() ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•ด์•ผ ํ•œ๋‹ค. ์ด ํ•จ์ˆ˜๋Š” 2๊ฐœ์˜ argument๋ฅผ ์ทจํ•˜๋Š”๋ฐ, ์ฒซ๋ฒˆ์งธ๋Š” update๊ฐ€ ํ•„์š”ํ•œ component์˜ state์™€ callback(optional)์ด๋‹ค. setState()๊ฐ€ ํ˜ธ์ถœ๋  ๋•Œ ์ž๋™์œผ๋กœ render ํ•จ์ˆ˜๊ฐ€ ์‹คํ–‰๋˜๋ฉฐ ํ•ด๋‹น ์‹œ์ ์— ์ƒํƒœ๊ฐ€ ๋ณ€ํ™”ํ•˜์ง€ ์•Š์€ property๋Š” ๊ธฐ์กด์˜ ์ƒํƒœ๋ฅผ ์œ ์ง€ํ•˜๊ณ  ๋ณ€๊ฒฝ๋œ ๋ถ€๋ถ„๋งŒ ๋ฐ˜์˜๋œ๋‹ค.
โŽ render ํ•จ์ˆ˜ ์•ˆ์— state๊ฐ€ ์žˆ์œผ๋ฉด ํ•ด๋‹น class๋Š” ๋ฌดํ•œ loop๊ฐ€ ๋  ๊ฒƒ์ด๋‹ค. ๐Ÿ˜“

{
  mood:   'great',
  hungry: false
}

this.setState({ hungry: true });


{
  mood:   'great',  //mood๋Š” ๋ณ€ํ•˜์ง€ ์•Š์Œ
  hungry: true
}
  • Call this.setState from another function

    . this.setState()๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๊ฐ€์žฅ ๋ณดํŽธ์ ์ธ ๋ฐฉ๋ฒ•์€ setState()๊ฐ€ ์ž‘์„ฑ๋œ ์‚ฌ์šฉ์ž ์ง€์ • ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๊ฒƒ์ด๋‹ค.

 class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = { weather: 'sunny' };
    this.makeSomeFog = this.makeSomeFog.bind(this);
  }

  makeSomeFog() {    //custom function
    this.setState({
      weather: 'foggy'
    });
  }
}

ย ย ย  . ์‚ฌ์šฉ์ž ์ง€์ • ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•  ๋•Œ ์ฃผ์˜ํ•ด์•ผ ํ•  ์ ์ด ์žˆ๋‹ค. ๋ฐ”๋กœ JavaScript๊ฐ€ eventHandler๋ฅผ bindingํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ์ธํ•ด์„œ attribute์— ํ• ๋‹น๋œ handler์˜ this๊ฐ€ ์œ ํšจํ•˜์ง€ ์•Š๊ฒŒ ๋œ๋‹ค๋Š” ์ ์ด๋‹ค.
โŽ eventHandler๋ฅผ this๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ •์˜ํ•  ๊ฒฝ์šฐ, constructor์— this.methodName = this.methodName.bind(this)๋ฅผ ๊ผญ ์ถ”๊ฐ€ํ•˜์—ฌ ํ•ด๋‹น method๊ฐ€ ํ˜„์žฌ obj๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ๊ฒƒ์ด๋ผ๊ณ  ์•Œ๋ ค์ค˜์•ผ ํ•œ๋‹ค.

profile
Turtle Never stop

0๊ฐœ์˜ ๋Œ“๊ธ€