账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    关于react组件class中state的在构造函数中的位置读取顺序
    38
    0

    问题描述

    在学习react官方文档context时发现了一个问题,构造函数中声明了一个箭头函数和一个state,如果把state放在了箭头函数上面就没办法实现按钮换肤(按钮点击无反应,但不会报错)。放在后面就可以。
    context-父子耦合-按钮换肤

    相关代码

    import...
    //Context
    import {ThemeContext, themes} from "./theme-context";
    //按钮组件
    import ThemeTogglerButton from './theme-toggler-btn';
    class App extends React.Component {
        constructor(props) {
            super(props);
            //state放在这里就无法正常换肤
            /*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')
    )
    

    其余的代码可以参考官方文档

    这个问题估计没耐心或者没兴趣的大佬会懒得看,所以拜托一下也正在学习react的大佬们了

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 旧城あい似梦 普通会员 1楼

      在React中,state是在类组件的构造函数中创建的。在React中,每个组件都是由state、react生命周期方法(如componentDidMountcomponentDidUpdatecomponentWillUnmount等)和render方法组成的。每个组件的状态是在其render方法中被初始化的。

      如果你想在类组件的构造函数中读取state的在初始化顺序,那么你应该首先在构造函数中初始化state,然后在使用state之前调用其他生命周期方法。

      例如,如果你有一个state对象state,并且你想要在构造函数中读取它,你可以这样做:

      ```javascript class MyComponent extends React.Component { constructor(props) { super(props); this.state = { count: 0, }; }

      // 其他生命周期方法和render方法

      componentDidMount() { // 使用state之前调用其他生命周期方法 this.setState({ count: this.state.count + 1, }); }

      // 其他生命周期方法和render方法 } ```

      在这个例子中,componentDidMount生命周期方法在state被初始化之前调用。在componentDidMount方法中,我们使用this.setState来更新state,并且在componentDidMount方法之后再使用this.setState来更新state。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部