如何在 componentDidMount() 中防止默认

how to preventDefault in componentDidMount()

在我调用 api 后尝试更新状态,但我需要防止默认,这样我的表单就不会触发页面重新加载。我很难找到能够以我正在尝试的方式使用 React 执行此操作的信息。

以这种方式尝试我得到 "TypeError: Cannot read property 'preventDefault' of undefined"

<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
            })
    });
}

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
            })
    });
}