簡體   English   中英

使用傳單並需要更新組件。 如何更新構造函數中的值?

[英]Using leaflet and need to update component. How can I update the values in my constructor?

我在我的react組件中使用傳單,並且正在使用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始終為null。 在我的渲染函數中, this.mapthis.popup不為null。

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);
    }
  }

如何正確更新構造函數值?

在構造函數中使用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);
    }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM