为什么e.preventDefault()会在提交时刷新页面?

问题描述 投票:0回答:2

我有一个搜索处理程序方法,当单击一个按钮时,它执行搜索(从API获取)。我没有像教程中所建议的那样添加e.preventDefault()来阻止页面提交,但是在执行搜索时似乎没有刷新页面。为了确保它没有被刷新,我将e.preventDefault()添加到搜索方法中,它实际上导致页面刷新而不显示结果 - 与预期相反。

造成这种情况的原因是什么,为什么没有e.preventDefault()我的页面没有提交?

这是我添加了e.preventDefault();的搜索方法。它在构造函数中绑定,并作为prop传递给搜索按钮(在另一个文件中)。

searchJokes(limit = 15, e) {
    e.preventDefault();
    // If nothing entered, user gets "Please fill out this field" message due to "required" attribute on input element
    if (this.state.searchTerm !== '') {
      this.setState({
        isFetchingJokes: true,
        isSearch: true
      });

      fetch(
        `https://icanhazdadjoke.com/search?term=${
          this.state.searchTerm
        }&limit=${limit}`,
        {
          method: 'GET',
          headers: {
            Accept: 'application/json'
          }
      })
        .then(response => response.json())
        .then(json => {
          let jokes = json.results;
          this.setState({
            jokes,
            isFetchingJokes: false
          });
        });
    }
  }

包含表单元素的功能组件(只有搜索按钮才会调用搜索方法):

const RetrievalForm = props => (
  <form>
    <input
      type="text"
      placeholder="Enter search term..."
      onChange={props.onSearchInputChange}
      required
    />
    <button onClick={props.onSearch} disabled={props.isSearching}>Search</button>
    <button onClick={props.onRandomize} disabled={props.isSearching}>
      Randomize
    </button>
  </form>
);

没有使用e.preventDefault();的完整代码:app.js retrieval-form.js

编辑:在教程中使用onSubmit而不是onClick。不知何故onClick实际上不会导致页面刷新,而onSubmit确实如此。所以我没有必要使用e.preventDefault()

编辑2:onClick搜索不会导致Chrome中的页面刷新,但它在Firefox中会发生。

javascript reactjs
2个回答
© www.soinside.com 2019 - 2024. All rights reserved.