鍍金池/ 問(wèn)答/HTML5  HTML/ 關(guān)于react組件class中state的在構(gòu)造函數(shù)中的位置讀取順序

關(guān)于react組件class中state的在構(gòu)造函數(shù)中的位置讀取順序

問(wèn)題描述

在學(xué)習(xí)react官方文檔context時(shí)發(fā)現(xiàn)了一個(gè)問(wèn)題,構(gòu)造函數(shù)中聲明了一個(gè)箭頭函數(shù)和一個(gè)state,如果把state放在了箭頭函數(shù)上面就沒(méi)辦法實(shí)現(xiàn)按鈕換膚(按鈕點(diǎn)擊無(wú)反應(yīng),但不會(huì)報(bào)錯(cuò))。放在后面就可以。
context-父子耦合-按鈕換膚

相關(guān)代碼

import...
//Context
import {ThemeContext, themes} from "./theme-context";
//按鈕組件
import ThemeTogglerButton from './theme-toggler-btn';
class App extends React.Component {
    constructor(props) {
        super(props);
        //state放在這里就無(wú)法正常換膚
        /*this.state = {
            theme: themes.dark,
            toggleTheme: this.toggleTheme
        }*/
        this.toggleTheme = () => {
            this.setState(state => ({
                theme:
                    state.theme === themes.dark
                        ? themes.light
                        : themes.dark
            }))
        }
        //state放在這里就可以正常切換按鈕的顏色
        this.state = {
            theme: themes.dark,
            toggleTheme: this.toggleTheme
        }
    }

    render() {
        return (
            <ThemeContext.Provider value={this.state}>
                <Content/>
            </ThemeContext.Provider>
        )
    }

}

function Content() {
    return (
        <div>
            <ThemeTogglerButton/>
        </div>
    )
}
ReactDOM.render(
    <App/>,
    document.getElementById('root')
)

其余的代碼可以參考官方文檔

這個(gè)問(wèn)題估計(jì)沒(méi)耐心或者沒(méi)興趣的大佬會(huì)懶得看,所以拜托一下也正在學(xué)習(xí)react的大佬們了

回答
編輯回答
汐顏

你在箭頭函數(shù)前后分別打印一下this吧

2017年7月11日 05:35