React 表单刷新整个页面 onSubmit 和 setState 不起作用
React form refreshes the entire page onSubmit and setState not working
我正在向 https://random-word-api.herokuapp.com/ 发出获取请求以获取一个词
我在我的页面上显示该词,并要求用户在下面的输入框中键入该词。
一旦用户键入它并按下提交或输入,我检查并查看单词是否正确,如果正确,我将执行另一个获取请求以获取新单词。但这会刷新我的整个页面,并且分数计数器不会增加
不知道我做错了什么。
event.preventDefault() 也无法正常工作
import React from 'react';
import getWord from './API/Word';
import key from './API/Key';
class App extends React.Component {
state = {
value: '',
word: null,
score: 0
}
handleSubmit(event) {
event.preventdefault();
if (this.state.word === this.state.value) {
this.setState({score: this.state.score + 1});
this.getWord();
}
}
getWord() {
getWord.get(`/word?key=${key}&number=1`)
.then(response => {
this.setState({word: response.data[0]})
});
}
componentDidMount() {
this.getWord();
}
render() {
return (
<div className = 'ui container'>
<p>The Word: {this.state.word}</p>
<br></br>
<form className = "ui form" onSubmit = {this.handleSubmit}>
<div className = "ui field">
<label>Type the word: </label>
<input
type = "text"
value = {this.state.value}
onChange = {(e) => this.setState({value: e.target.value})}
/>
</div>
<button>Submit</button>
</form>
<br></br>
Score: {this.state.score}
</div>
)
}
}
export default App
我在控制台中很快收到此错误消息,然后它就消失了
handleSubmit
函数有两个问题。
您在 preventDefault
中有错字。需要大写的D.
并且因为您使用普通声明编写了函数,所以 this
未绑定。所以你要么必须自己绑定它
onSubmit = {this.handleSubmit.bind(this)}
或更好地将其转换为箭头函数:
handleSubmit = (event) => {
event.preventDefault();
...
}
有了这个,函数将被 React 自动绑定。
import React from 'react';
import getWord from './API/Word';
import key from './API/Key';
class App extends React.Component {
state = {
value: '',
word: null,
score: 0
}
handleSubmit(event) {
event.preventdefault();
if (this.state.word === this.state.value) {
this.setState({score: this.state.score + 1});
this.getWord();
}
}
getWord() {
getWord.get(`/word?key=${key}&number=1`)
.then(response => {
this.setState({word: response.data[0]})
});
}
componentDidMount() {
this.getWord();
}
render() {
return (
<div className = 'ui container'>
<p>The Word: {this.state.word}</p>
<br></br>
<form className = "ui form" onSubmit = {this.handleSubmit}>
<div className = "ui field">
<label>Type the word: </label>
<input
type = "text"
value = {this.state.value}
onChange = {(e) => this.setState({value: e.target.value})}
/>
</div>
<button>Submit</button>
</form>
<br></br>
Score: {this.state.score}
</div>
)
}
}
export default App
我在控制台中很快收到此错误消息,然后它就消失了
handleSubmit
函数有两个问题。
您在 preventDefault
中有错字。需要大写的D.
并且因为您使用普通声明编写了函数,所以 this
未绑定。所以你要么必须自己绑定它
onSubmit = {this.handleSubmit.bind(this)}
或更好地将其转换为箭头函数:
handleSubmit = (event) => {
event.preventDefault();
...
}
有了这个,函数将被 React 自动绑定。