React Context和ES6类

时间:2017-03-21 02:34:19

标签: javascript reactjs react-native

如果我有ES6课程,

export default class WSConn {
    constructor() {
        this.conn = null;
        this.event_id = null
        this.navigator = null;
    }

    getEventID() {
        return this.event_id
    }

    setEventID(event_id) {
        this.event_id = event_id
    }
}

我将它传递给上下文(并初始化),

class ContextProvider extends Component {
    getChildContext() {
        return {
            logger: new appLogger(Platform.OS),
            websocket: new WSConn()
        };
    } 

    render() {
        return this.props.children
    }
}

ContextProvider.childContextTypes = {
  websocket: React.PropTypes.object
};

function wrapWithContextProvider(Comp) {
  return (props) => {
    return (
        <ContextProvider>
            <Comp {...props} />
        </ContextProvider>
    );
  };
}

我在类中设置数据,为什么当我获取数据时,它仍为空?

如何在我通过反应上下文传递的es6类中设置和存储数据而不会丢失任何状态?或者我应该把它作为一个全球对象?

1 个答案:

答案 0 :(得分:0)

解决方案是我这样做:

class SomeClass extends Component {
    getChildContext() {
    return {
        monitor: new Monitoring(url)
    }
  }
}

class Monitoring {
    constructor(url) {
    this.url = url
  }
  getUrl() {
    return this.url
  }
}

而不是:

class SomeClass extends Component {
    constructor() {
    this.monitor = new Monitoring(url)
  }

    getChildContext() {
    return {
        monitor: this.monitor
    }
  }
}

class Monitoring {
    constructor(url) {
    this.url = url
  }
  getUrl() {
    return this.url
  }
}