reactjs - 无法读取 API 调用中未定义的属性“状态”
问题描述
我在反应中有以下组件
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
cityName: "",
weather: ""
}
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
fetch(`https://api.weatherapi.com/v1/current.json?key=.....&q=${this.state.cityName}&aqi=no`)
.then(response => response.json())
.then(json => {
this.setState({ weather: json});
});
}
handleChange(event) {
this.setState({cityName: event.target.value});
}
render() {
return (
<center>
<p><font color="bluesky" size="10">Weather</font></p>
<div class="card-body">
<input type="text" value={this.state.value} onChange={this.handleChange} placeholder="Type the name of city"></input>
<h3>{this.state.cityName}</h3>
</div>
<div>
<button className="btn btn-secondary btn-sm" onClick={this.componentDidMount}>Check weather</button>
</div>
</center>
);
}
}
对于这行代码,
fetch(`https://api.weatherapi.com/v1/current.json?key=...&q=${this.state.cityName}&aqi=no`)
我得到下一个错误“TypeError:无法读取未定义的属性'状态'”。我是新手,有人可以帮我解决这个错误吗?
解决方案
您正在调用组件生命周期方法来处理表单提交。就像您拥有 changeHandler 一样创建一个 submitHandler ,它应该可以正常工作。
onSubmit = () => {
fetch(`https://api.weatherapi.com/v1/current.json?key=.....&q=${this.state.cityName}&aqi=no`)
.then(response => response.json())
.then(json => {
this.setState({ weather: json});
});
}
该按钮将被配置为:
<button className="btn btn-secondary btn-sm" onClick={this.onSubmit}>Check weather</button>
专业提示:使用箭头函数在组件中定义自定义方法。
注意:您需要配置 API 密钥并正确处理响应,在第二个 .then() 中使用 console.log(json) 并查看您得到了什么。
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
cityName: "",
weather: ""
}
}
onSubmit = () => {
fetch(`https://api.weatherapi.com/v1/current.json?key=.....&q=${this.state.cityName}&aqi=no`)
.then(response => response.json())
.then(json => {
this.setState({ weather: json});
});
}
handleChange = (event) => {
this.setState({cityName: event.target.value});
}
render() {
return (
<center>
<p><font color="bluesky" size="10">Weather</font></p>
<div class="card-body">
<input type="text" value={this.state.cityName} onChange={this.handleChange} placeholder="Type the name of city"></input>
<h3>{this.state.weather}</h3>
</div>
<div>
<button className="btn btn-secondary btn-sm" onClick={this.onSubmit}>Check weather</button>
</div>
</center>
);
}
}
推荐阅读
- php - 为什么我不能使用 PHP artisan serve 运行我的 laravel 应用程序?
- r - 在 Windows 命令行中使用 UTF8 查询的 search_tweets 返回 0 输出
- c++ - C++ 模棱两可的模板重载
- neo4j - Neo4j 密码查询过滤关系计数
- java - java.io.Serializable android.os.Bundle.getSerializable(java.lang.String)' 在空对象引用上
- python - 改进神经网络以识别手语
- php - 这种方式使用自定义字段来更改 WooCommerce 中的“添加到卡片文本”好吗?
- azure - 让我们加密 Azure 错误“找不到 Web 应用程序”
- vb.net - 将 VB6 迁移到 VB.net 记录集和数据表
- red - 红色到 dotnet 或 java android:.Net -> Red(未实现)