[React 03] state


Posted by tzutzu858 on 2021-04-25

state 與改變 state


function component

State

可透過 useState 設定 state 初始值,再透過 setState 去改變 state
舉例 : 在 Counter 這個 component 下面,要有一個 state ,它的名字叫做 value,它的初始值是 99,要改狀態就呼叫 setValue

function Counter() {
    const [value, setValue] = React.useState(99)
    return <h1>{value}</h1> // 顯示 99
}
function Counter() {
    const [value, setValue] = React.useState(1)
    function handleClick() {
      setValue(value + 1)
    }
    return <h1 onClick={handleClick}>{value}</h1>
}


上面是用 CodeSandbox 進行測試



Class component

每一個 Component 被建立的時候,都會呼叫 constructor,在呼叫的時候必須 call super(),因為要繼承 component

import React, { Component } from 'react'

class App extends Component {  
    constructor() {
        super()
        this.state = {
            counter: 1
        }
    }
    render() {
        return (
            <div>
                <h1>test</h1>
                <div>{this.state.counter}</div>
            </div>
        )
    }
}

export default App

改變 state 狀態一定要用 setState()

onClick={()=>{
     this.setState({
          counter: this.state.counter + 1
     })
}}

onClick 裡不能用下面這方法來改變 state

this.state.counter++; // 不會報錯,但也沒有任何反應

這樣寫起來有點混亂,所以把 setState() 抽出來額外寫個 function 比較好看

import React, { Component } from 'react'

class App extends Component {
    constructor() {
        super()
        this.state = {
            counter: 1
        }
    }

    handleClick() {
        this.setState({
            counter: this.state.counter + 1
        })
    }

    render() {
        return (
            <div>
                <h1 onClick={this.handleClick}>click me</h1>
                <div>{this.state.counter}</div>
            </div>
        )
    }
}

export default App

但上述這樣寫會報錯

Cannot read property 'setState' of undefined

這跟 this 值有關
第一種解法是一開始在 constructor 的時候,直接用 bind() 把他 bind 下來

this.handleClick = this.handleClick.bind(this)

第二種解法
在onClick 那邊先 bind()

onClick={this.handleClick.bind(this)}

this 在程式碼的哪邊無關,跟 function 怎麼被呼叫有關
複習筆記 : [進階 js 11] this










Related Posts

變數及規則、Undefined、Null、NaN差異?

變數及規則、Undefined、Null、NaN差異?

342. Power of Four

342. Power of Four

【JS上課筆記】JavaScript 物件導向:建構式、class、原型鏈

【JS上課筆記】JavaScript 物件導向:建構式、class、原型鏈


Comments