【发布时间】:2019-04-20 21:33:01
【问题描述】:
我有一个搜索处理程序方法,该方法在单击按钮时执行搜索(从 API 获取)。我没有按照教程中的建议添加e.preventDefault() 来阻止页面提交,但是执行搜索时似乎没有刷新页面。为了确保它没有被刷新,我在搜索方法中添加了e.preventDefault(),它实际上导致页面刷新而不显示结果——与预期相反。
是什么原因造成的,为什么没有e.preventDefault(),我的页面在提交时没有刷新?
这是我添加了e.preventDefault(); 的搜索方法。它绑定在构造函数中并作为道具传递给搜索按钮(在另一个文件中)。
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 中会。
【问题讨论】:
-
您需要在表单事件中添加阻止默认值,而不是点击事件。
<form onSubmit={e => e.preventDefault()}> -
你的
<form ... >看起来怎么样?? -
添加了表单的代码——它目前没有 onSubmit 处理程序
-
在哪里调用
searchJokes? -
它作为道具点击处理程序传递给搜索按钮。
prop.onSearch对应searchJokes()方法(渲染包含表单的组件时,有onSearch={this.searchJokes})。
标签: javascript reactjs