2017-06-20 34 views
0

我有一個警報組件,它在主要組件中向componentWillMount添加代碼後立即渲染兩次。 The project is an expo project當可見性狀態未被更改時,爲什麼反應原生警報組件會呈現兩次?

我已經通過將控制警報組件可見性的屬性設置爲false,然後調用this.startAlert()來更改componentWillMount過程中的可見性狀態。在解決方案之前,僅在對話框上按下按鈕後才能更改可見性狀態。

This Works。它顯示一次警報對話框。 this.startAlert();在承諾中執行。

componentWillMount() { 

    const setPosition = (pos) => { 

     console.log(pos) ; 

    // We need the "latitude" and the "longitude" 
    // in order to lookup the "address" from the 
    // Google maps API. 
    const { 
     coords: { 
     latitude, 
     longitude, 
     }, 
    } = pos; 

    // Fetches data from the Google Maps API then sets 
    // the "address" state based on the response. 
    fetch(`${URL}${latitude},${longitude}`) 
     .then(resp => resp.json(), e => console.error(e)) 
     .then(({ 
     results: [ 
      { formatted_address }, 
     ], 
     }) => { 
      this.setAddress(formatted_address) ; 
      this.startAlert() ;   
     }); 
    } ; 


    navigator.geolocation.getCurrentPosition(setPosition) ; 

} 

而失敗。警報組件顯示兩次。 this.startAlert();被稱爲獲取諾言之外。

componentWillMount() { 

    const setPosition = (pos) => { 

     console.log(pos) ; 

    // We need the "latitude" and the "longitude" 
    // in order to lookup the "address" from the 
    // Google maps API. 
    const { 
     coords: { 
     latitude, 
     longitude, 
     }, 
    } = pos; 

    // Fetches data from the Google Maps API then sets 
    // the "address" state based on the response. 
    fetch(`${URL}${latitude},${longitude}`) 
     .then(resp => resp.json(), e => console.error(e)) 
     .then(({ 
     results: [ 
      { formatted_address }, 
     ], 
     }) => { 
      this.setAddress(formatted_address) ;  
     }); 
    } ; 

    this.startAlert() ; 
    navigator.geolocation.getCurrentPosition(setPosition) ; 

} 

當可見性狀態沒有改變時,爲什麼反應本機警報組件會呈現兩次?

編輯:設置地址的代碼。

// Getter for "Immutable.js" state data... 
get data() { 
    return this.state.data; 
} 

// Setter for "Immutable.js" state data... 
set data(data) { 
    this.setState({ data }); 
} 

setAddress = (address) => { 
    this.data = this.data.set('address', address) ; 
} 
+0

'this.setAddress'究竟做了什麼?它是否更新狀態? – Raymond

+0

爲什麼你有兩個setPosition函數? –

+0

this.setAddress確實更新狀態。它設置一個地址。 –

回答

1

可幫助突出特別是兩個代碼段之間,因爲乍看之下,他們看起來大致相同的不同閱讀的哪怕是一點點。 this.setAddress(...)的定義似乎沒有包含在內,但是它是否在傳遞中調用this.setState(...)this.setState(...)導致重新呈現this

相關問題