【发布时间】:2018-02-15 21:36:34
【问题描述】:
这是我第一次尝试一个简单的 React 应用程序。使用 Openweather API 和 AXIOS。我参加了 Stephen Grider 关于 Udemy 的课程,现在我正在尝试自己创建一些东西,但是在组件之间传递数据时仍然遇到问题。我有一个 SearchBar 组件,我希望能够将输入值传递给父组件的状态,因此我可以在每次搜索时更新它并将其呈现到 DOM 中。但是,我一直遇到错误。我尝试将一个函数作为道具传递给我的 SearchBar 组件,但出现错误:
setState(...):只能更新一个挂载或挂载的组件。这通常意味着您在未安装的组件上调用了 setState()。这是一个无操作。请检查 App 组件的代码。
citySearch 未定义
这让我很困惑,因为我试图从课程中复制确切的步骤,它似乎工作得很好。但同样,我对此很陌生,所以可能只是我犯了某种菜鸟错误。任何提示将不胜感激。
在下面检查我的代码:
App.js
import React, { Component } from 'react';
import './App.css';
//Libraries
import axios from 'axios';
//Components
import SearchBar from './Components/search-bar';
class App extends Component {
constructor(props){
super(props);
this.state = {
city: 'London',
country: 'uk',
temperature: 0,
humidity: 0,
pressure: 0
}
//Axios call
let city = this.state.city;
let country = this.state.country;
axios
.get(`http://api.openweathermap.org/data/2.5/weather?APPID=${API_KEY}&q=${city},${country}`)
.then(function(response) {
this.setState({
city: response.data.name,
country: response.data.name,
temperature: response.data.main.temp,
humidity: response.data.main.humidity,
pressure: response.data.main.pressure
});
}.bind(this))
.catch(function(error) {
console.log(error);
});
this.citySearch('London');
}
citySearch(city){
this.setState({city})
}
render() {
return (
<div className="container">
<h1 className="display-1 text-center">Weather App</h1>
<SearchBar onSearchTermChange={citySearch} />
</div>
);
}
}
export default App;
搜索栏组件:
import React, { Component } from 'react';
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = {
city: ""
};
}
render() {
return (
<input
value={this.state.city}
onChange={this.onHandleChange}
className="form-control mt-3"
placeholder="Enter a city name..."
type="text"
/>
);
}
onHandleChange(city) {
this.setState({ city });
this.props.onSearchTermChange(city);
}
}
export default SearchBar;
【问题讨论】:
-
在
componentDidMount中调用axios,而不是构造函数。你可以this.state = { city: 'London' }- 不要在那里使用 setState。 -
你为什么要在构造函数中做所有事情
标签: javascript reactjs dom components