我正在尝试恰当地组织我对openweatherapi的API调用,只是尝试创建一个简单的天气应用程序,当用户输入一个城市时,天气预报就会呈现到页面上。这就是我到目前为止所做的,也试图阻止当按钮被按下时页面刷新的默认操作。我正在使用react。
class App extends Component {
getWeatherData = (userInput, event) => {
event.preventDefault();
axios({
url: "http://openweathermap.org/data/2.5/weather/",
method: "GET",
dataType: "json",
data: {
q: userInput,
API_KEY: "d108038ec889cfe762230283abaa7c7b"
}
}).then(res => {
console.log(res);
this.setState({});
});
};
./Form。js如下所示
class Form extends Component {
render() {
return (
<div>
<form onSubmit={(this.props.getWeather, e)}>
<input type="text" name="city" placeholder="City..." />
<input type="text" name="country" placeholder="Country" />
<button>Get Weather</button>
</form>
</div>
);
}
}
错误:
./src/Form.js
Line 7: 'e' is not defined no-undef
发布于 2019-05-31 06:49:48
使用类组件,我会这样做:
(每个类/函数应该拆分到不同的文件中)
/**
* This is just a helper to encapsulate the weather fetching logic
*/
function getWeatherFromInput({ city, country }) {
const query = `${city},${country}`;
return axios({
method: 'GET',
url: `http://openweathermap.org/data/2.5/weather?${query}`,
responseType: 'json'
});
}
/**
* Here is the specific form
*/
export class WeatherForm extends React.Component {
constructor(props) {
super(props);
this.state = {
city: '',
country: ''
};
}
handleSubmit = (event) => {
event.preventDefault();
this.props.onSubmit(this.state);
};
handleInputChange = (event) => {
const { name, value } = event.target;
this.setState({ [name]: value });
};
render() {
const { city, country } = this.state;
return (
<form onSubmit={this.handleSubmit}>
<input
type='text'
name='city'
value={city}
onChange={this.handleInputChange}
placeholder='City...'
/>
<input
type='text'
name='country'
value={country}
onChange={this.handleInputChange}
placeholder='Country'
/>
<button type='submit'>Get weather</button>
</form>
);
}
}
/**
* And how you use it in your App
*/
export class App extends React.Component {
constructor() {
this.state = {
weather: {}
};
}
/**
* The userInput is provided by the WeatherForm
*/
handleSubmit = (userInput) => {
getWeatherFromInput(userInput).then((response) => {
this.setState({ weather: response.data });
});
};
render() {
return <WeatherForm onSubmit={handleSubmit} />;
}
}
发布于 2019-05-31 05:31:36
你可以将表单移动到你的app类中,在组件之间传递表单数据在react中工作得很好。
class App extends Component {
getWeatherData = (event) => {
const userInput = {
event.target.city.value,
event.target.country.value
}
event.preventDefault();
axios({
url: "http://openweathermap.org/data/2.5/weather/",
method: "GET",
dataType: "json",
data: {
q: userInput,
API_KEY: "d108038ec889cfe762230283abaa7c7b"
}
}).then(res => {
console.log(res);
this.setState({});
});
render() {
return (
<div>
<form onSubmit={this.getWeatherData}>
<input type="text" name="city" placeholder="City..." />
<input type="text" name="country" placeholder="Country" />
<button>Get Weather</button>
</form>
</div>
);
}
}
您也不需要将事件指定为可以通过使用userInput关键字访问值来在函数中设置的参数。
https://stackoverflow.com/questions/56385776
复制相似问题