1
我必須將MyWeather中的數據傳遞給MyWeatherData,並且在MyWeatherData中使用componentDidMount時,會出現道具不會傳入子組件的情況。現在我在MyWeatherData中使用componentDidUpdate並且它可以工作,但是它會產生一個錯誤:只能更新已安裝或掛載的組件。請檢查...組件的代碼。有誰知道如何糾正這個問題?ComponentDidMount不起作用 - 道具不傳遞給子組件
當我通過:<MyWeatherData lat="53.0038" lon="20.0458"/>
它與ComponentDidMount一起使用。
import React, {Component} from "react";
import MyWeatherData from "./MyWeatherData";
export default class MyWeather extends Component {
constructor() {
super();
this.state = {
latitude: "",
longitude: ""
}
this.getMyLocation = this
.getMyLocation
.bind(this)
}
componentDidMount() {
this.getMyLocation()
}
getMyLocation() {
const location = window.navigator && window.navigator.geolocation
if (location) {
location.getCurrentPosition(pos => {
this.setState({latitude: pos.coords.latitude, longitude: pos.coords.longitude})
}, (error) => {
this.setState({latitude: 'err-latitude', longitude: 'err-longitude'})
})
}
}
render() {
const {latitude, longitude} = this.state;
return (
<div>
<MyWeatherData lat={latitude} lon={longitude}/>
</div>
)
}
}
import React, {Component} from "react";
import axios from "axios";
export default class MyWeatherData extends Component {
constructor() {
super();
this.state = {
descriptionMain: "",
description: "",
temperature: null,
weatherIcon: "",
name: ""
}
}
componentDidUpdate =() => {
this.getMyWeather();
}
getMyWeather =() => {
const lat = this.props.lat;
const lon = this.props.lon;
const API_KEY = "e6f4d816d3ade705ec1d8d9701b61e14";
const weatherURL = `https://api.openweathermap.org/data/2.5/weather?APPID=${API_KEY}&units=metric&lat=${lat}&lon=${lon}`;
axios
.get(weatherURL)
.then(res => {
this.setState({descriptionMain: res.data.weather[0].main, description: res.data.weather[0].description, temperature: res.data.main.temp, weatherIcon: res.data.weather[0].icon, name: res.data.name});
})
.catch(error => {
console.log(error);
});
}
render() {
const {descriptionMain, description, temperature, weatherIcon, name} = this.state;
return (
<div>
<h2>Weather for: {name}</h2>
<h4>Sky: {description}</h4>
<h5>Description: {descriptionMain}</h5>
<span className="temperature">{temperature}
°C</span>
{weatherIcon
? (<img
src={`http://openweathermap.org/img/w/${weatherIcon}.png`}
alt={`${description}`}/>)
: null}
</div>
)
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>