0

I have an alert component that renders twice as soon as I add code to componentWillMount in the main component. The project is an expo project

I've worked around it by setting the property controlling the visibility of the alert component to false and then calling this.startAlert() which changes the visibility state within the componentWillMount procedure. Before the workaround the visibility state was only changed after pressing a button on the dialog.

This works. It shows the alert dialog once. this.startAlert() ; is executed in the promise.

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

}

Whereas this fails. The alert component is shown twice. this.startAlert() ; is called outside of the fetch promise.

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

}

Why would a react-native alert component render twice when the visibility state was not changed ?

Edit: Code that sets the address.

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

1 回答 1

1

可能有助于突出两个代码片段之间的特殊差异,因为乍一看,甚至一点点阅读它们看起来几乎相同。的定义this.setAddress(...)似乎不包括在内,但它是否传递调用this.setState(...)this.setState(...)导致重新渲染this.

于 2017-06-20T21:40:40.330 回答