2017-12-31 159 views
1

내가 navigator.geolocation.getCurrentPosition를 사용하여 사용자의 컴퓨터에서 받았다 좌표()는 위치 정보를 얻기 및 componentDidMount()에서 Ajax 요청을 보내기

내 문제는 내가 봉착되는 문제와 날씨 API를 호출하기 위해 노력하고있어 모든 것이 주어진다면 올바른 방법을 찾아 내면 비동기 적으로 실행됩니다. 그런 다음 componentDidMount()를 사용하여 적절한 해결 방법을 찾았다 고 생각했지만 불행히도 작동하지 않았습니다.

은 여기 내 codepen (산세의 API 키)

그리고 여기에 코드입니다 :

state = { 
     data: "Please wait while you're weather is loading...", 
    } 
    componentDidMount() { 
     this.state.hasOwnProperty('uri') ? 
      fetch(this.state.uri).then((res) => res.json()) 
      .then((data) => this.setState({ 
       data: { 
        tempString: data.current_observation.temperature_string, 
        realTemp: data.current_observation.feelslike_string, 
        skyImg: data.current_observation.icon_url.substring(0, 4) + 's' + data.current_observation.icon_url.substring(4), 
        location: data.current_observation.display_location.full, 
        temp_f: data.current_observation.temp_f, 
       } 
      })) 
      .catch((err) => console.log(err.message)) 
     : navigator.geolocation.getCurrentPosition((pos) => { 
      this.setState({ 
       uri: "https://api.wunderground.com/api/{API GOES HERE}/conditions/q/" + pos.coords.latitude.toString() + "," + pos.coords.longitude.toString() + ".json" 
      }) 
      console.log(this.state.uri) 
     }) 
    } 

다음과 같이 모든 실행 방법의 나의 이해는 다음과 같습니다

  1. 초기 구성 요소는
  2. 를 렌더링
  3. componentDidMount()가 호출되고 if 문을 살펴 봅니다.
  4. URI 속성을 찾을 수 없으므로 새로운 URI 속성으로 상태를 설정하고 getCurrentPosition() 호출을 시작합니다. 내 지식으로 this.setState가 다시 렌더링을 트리거 한 다음 ...)
  5. componentDidMount 잘 모르겠어요하지만

를 실행하지 않는()() 다시 실행되지만이 시간이 가져 알 수없는 이유로 URI 속성

  • 을 발견 지금 URI 속성이 있지만, 내 추측이다 , 시간이 지남에 따라 새로운 componentDidMount()가 실행되고, 프로그램은 여전히 ​​그것을 설정하는 것을 알아내는 과정에 있습니다. 그러나 나는 완전히 틀릴 수도 있습니다. componentDidMount()가 URI 속성을 보지 않고 계속적으로 다시 렌더링하는 무한 루프를 만들 수도있었습니다.

  • +1

    왜 componentDidMount가 두 번 이상 실행됩니까? 구성 요소가 마운트 될 때 한 번만 실행됩니다. – brub

    +0

    고마워요! 나는 사실을 완전히 간과했다 componentDidMount 초기 설치에, 그리고 다시 렌더링하지 않습니다. –

    답변

    1

    as @ brub said : componentDidMount는 ui가 얼마나 업데이트 되더라도 두 번 이상 실행되지 않습니다. 솔루션으로 componentDidUpdate를 사용하여 종료되었습니다. 이제 코드는 다음과 같습니다.

    state = { 
         data: "Please wait while you're weather is loading...", 
        } 
        componentDidMount() { 
         navigator.geolocation.getCurrentPosition((pos) => { 
          this.setState({ 
           uri: "https://api.wunderground.com/api/{API GOES HERE}/conditions/q/" + pos.coords.latitude.toString() + "," + pos.coords.longitude.toString() + ".json" 
          }) 
         }) 
        } 
        componentDidUpdate() { 
         fetch(this.state.uri).then((res) => res.json()) 
         .then((data) => this.setState({ 
          data: { 
           tempString: data.current_observation.temperature_string, 
           realTemp: data.current_observation.feelslike_string, 
           skyImg: data.current_observation.icon_url.substring(0, 4) + 's' + data.current_observation.icon_url.substring(4), 
           location: data.current_observation.display_location.full, 
           temp_f: data.current_observation.temp_f, 
          } 
         })) 
          .catch((err) => console.log(err.message)) 
        }