내가 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)
})
}
다음과 같이 모든 실행 방법의 나의 이해는 다음과 같습니다
- 초기 구성 요소는 를 렌더링
- componentDidMount()가 호출되고 if 문을 살펴 봅니다.
- URI 속성을 찾을 수 없으므로 새로운 URI 속성으로 상태를 설정하고 getCurrentPosition() 호출을 시작합니다. 내 지식으로 this.setState가 다시 렌더링을 트리거 한 다음 ...)
- componentDidMount 잘 모르겠어요하지만
를 실행하지 않는()() 다시 실행되지만이 시간이 가져 알 수없는 이유로 URI 속성
왜 componentDidMount가 두 번 이상 실행됩니까? 구성 요소가 마운트 될 때 한 번만 실행됩니다. – brub
고마워요! 나는 사실을 완전히 간과했다 componentDidMount 초기 설치에, 그리고 다시 렌더링하지 않습니다. –