RN的单例

直接上代码

import React,{Component} from 'react';
let instance = null;

export default class AppDataManager extends Component {
    constructor(props){
        super(props);
        if(!instance){
            instance = this;
            
            console.warn('creat ....');
            //注意1:一定要在if内部,这里只能执行一次
            this.state = {
                userInfo:{},
            }
        }
        
        return instance;
        
    }
    
    static shareInstance(){
        let singleton = new AppDataManager();
        return singleton;
    }

    setUserInfo(info){
        //注意2:这里不能用setstate
        this.state.userInfo = info;
    }

    getUserInfo(){
        return this.state.userInfo;
    }
    
}


疑问,注意2哪里不知道为啥不能用setState来赋值。求告知!!!

你可能感兴趣的:(RN的单例)