Javascript 使用传单并需要更新组件。如何更新构造函数中的值?

Javascript 使用传单并需要更新组件。如何更新构造函数中的值?,javascript,reactjs,Javascript,Reactjs,我在react组件中使用传单,并且使用脚本加载库加载所有必要的脚本 我的构造函数中包含以下内容: constructor(props) { super(props); this.map = null; this.popup = null; } 我正在加载这样的传单: componentWillReceiveProps({ isScriptLoaded, isScriptLoadSucceed }) { if (isScriptLoaded &&

我在react组件中使用传单,并且使用脚本加载库加载所有必要的脚本

我的构造函数中包含以下内容:

constructor(props) {
    super(props);
    this.map = null;
    this.popup = null;
  }
我正在加载这样的传单:

componentWillReceiveProps({ isScriptLoaded, isScriptLoadSucceed }) {
    if (isScriptLoaded && !this.props.isScriptLoaded) {
      if (isScriptLoadSucceed) {
        this.map = L.map(this.refs.map);

   ///////
        this.popup = L.popup();
   ///////
但是,我的类中有一个函数,用于处理
onClickMap(e)
this.map
this.popup
始终为空。在我的渲染函数中,
this.map
this.popup
不为空

onClickMap(event) {
    console.log('on click', this.popup, this.map);  // both null
    if (this.popup) {
      this.popup
        .setLatLng(event.latlng)
        .setContent('You clicked the map at ' + event.latlng.toString())
        .openOn(this.map);
    }
  }

如何正确更新构造函数值

在构造函数中使用
此.state

constructor(props) {
    super(props);
    this.state = {
        map: null,
        popup: null
    }
}
并在componentWillReceiveProps中使用
setState

componentWillReceiveProps({ isScriptLoaded, isScriptLoadSucceed }) {
    if (isScriptLoaded && !this.props.isScriptLoaded) {
      if (isScriptLoadSucceed) {        
        this.setState({
            map: L.map(this.refs.map),
            popup: L.popup()
        });
   ///////
您可以从
this.state
获取它

onClickMap(event) {
    console.log('on click', this.state.popup, this.state.map);  // both null
    if (this.state.popup) {
      this.state.popup
        .setLatLng(event.latlng)
        .setContent('You clicked the map at ' + event.latlng.toString())
        .openOn(this.state.map);
    }
  }

谢谢如果你不介意的话,你能解释一下什么时候使用构造函数吗?@user1354934检查一下,那么什么是实现这个的最好方法呢。你会把
onmaplick
放在哪里?我不明白。在类中单击
onmapplick
没有问题。是的。谢谢你的帮助,我现在明白了:)。我只是想知道你会怎么做。使用状态?