在我调用api之后尝试更新状态但我需要阻止默认,因此我的表单不会触发页面重新加载。我很难找到信息,以便能够以我尝试的方式使用React。
尝试这种方式我得到" TypeError:无法读取属性' preventDefault'未定义"
<form className="form-inline" onSubmit={this.componentDidMount} >
<input
placeholder="Search your city!"
className="form-control"
value={this.state.term}
onChange={this.onInputChange}></input>
<button
type="submit"
className="btn btn-default">Search</button>
</form>
componentDidMount(event) {
event.preventDefault();
const API_KEY = 'ju2nvu4nvun42vgrw';
const ROOT_URL = `http://api.openweathermap.org/data/2.5/forecast?
appid=${API_KEY}`;
const city = this.state.term;
const url = `${ROOT_URL}&q=${city}`;
axios.get(url)
.then(function (response) {
this.setState({
days: response.data
})
});
}
答案 0 :(得分:1)
componentDidMount
是lifeCycle
函数,你不应该直接调用函数,而是在一个单独的函数中调用ajax请求并调用它
<form className="form-inline" onSubmit={this.handleSubmit} >
<input
placeholder="Search your city!"
className="form-control"
value={this.state.term}
onChange={this.onInputChange}></input>
<button
type="submit"
className="btn btn-default">Search</button>
</form>
handleSubmit(event) {
event.preventDefault();
const API_KEY = 'ju2nvu4nvun42vgrw';
const ROOT_URL = `http://api.openweathermap.org/data/2.5/forecast?
appid=${API_KEY}`;
const city = this.state.term;
const url = `${ROOT_URL}&q=${city}`;
axios.get(url)
.then(function (response) {
this.setState({
days: response.data
})
});
}