2017-01-21 24 views
0

我在我的反应组件中使用了传单,我正在使用scriptLoading库来加载所有必需的脚本。使用小册子并需要更新组件。我怎样才能更新我的构造函数中的值?

我在构造函数如下:

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.mapthis.popup始终为空。在我的渲染功能中,this.mapthis.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); 
    } 
    } 

如何正确更新构造函数值?

回答

1

使用this.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); 
    } 
    } 
+0

谢谢!如果你不介意,你可以解释何时使用构造函数吗? – user1354934

+0

@ user1354934检查此https://facebook.github.io/react/docs/react-component.html#constructor –

+0

然后实现这个最好的方法是什么? http://leafletjs.com/examples/quick-start/。你会在哪里放置'onMapClick'? – user1354934

相关问题