我正在React中构建一个应用程序。我是React的新手,请多多包涵。这个问题很简单。我正在创建由API调用的三个组件(我正在使用axios来调用API),但是它们根本不会呈现。我不确定自己在做什么错。
private ObservableCollection<SDH_CRModul_Sniffer> myGridData;
public ObservableCollection<SDH_CRModul_Sniffer> MyGridData
{
get { return myGridData; }
set
{
if (myGridData == value) return;
myGridData = value;
OnPropertyChanged("MyGridData");
}
}
然后我在App.js上调用该组件
import React, { Component } from "react";
import axios from "axios";
class Temperature extends Component {
showTemperature = () => {
let apiKey = "4cc79448ae57aa2b8557ec4dcd604fac";
let city = "Lisbon,pt";
let url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
axios.get(url).then(function(response) {
let temp = Math.round(response.data.main.temp);
return temp;
});
};
render() {
return <div>{this.showTemperature()}</div>;
}
}
export default Temperature;
在App功能内。当我调用组件时,没有任何渲染。任何提示或我在做什么错?谢谢。
PS:我正在将组件导入App:
<div>
<Temperature />
</div>
编辑:我想补充一下,我使用香草JavaScript完成了相同的应用,并且该API工作正常。
答案 0 :(得分:1)
尝试利用状态来存储您的温度值,如下所示:
import React, { Component } from "react";
import axios from "axios";
class Temperature extends Component {
constructor(props) {
super(props);
this.state = {
temp: 'Error' // Add default value to help determine if error is api call.
};
this.showTemperature = this.showTemperature.bind(this); // Bind 'this' context
}
showTemperature() { // This is how to properly declare a method in react.
let apiKey = "4cc79448ae57aa2b8557ec4dcd604fac";
let city = "Lisbon,pt";
let url = `https://api.openweathermap.org/data/2.5/weather?
q=${city}&appid=${apiKey}&units=metric`;
axios.get(url).then(function(response) {
let temp = Math.round(response.data.main.temp);
if (temp) { // Don't setstate if temp is undefined.
this.setState({temp: temp}); // Set your state
}
});
};
componentDidMount() {
this.showTemperature(); // Call your method on mount.
}
render() {
return <div>{this.state.temp}</div>;
}
}
export default Temperature;
我添加了注释,以解释您的代码中的其他错误。您应该可以从这里更好地进行故障排除。
答案 1 :(得分:0)
您必须像这样在App.js中导入温度
import Temperature from 'path'
答案 2 :(得分:0)
您的showTemperature方法返回未定义。这就是为什么它不呈现任何内容。