【问题标题】:React form refreshes the entire page onSubmit and setState not workingReact 表单刷新整个页面 onSubmit 和 setState 不起作用
【发布时间】:2019-07-27 11:10:52
【问题描述】:

我正在向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

我在控制台中很快收到此错误消息,然后它消失了

【问题讨论】:

    标签: javascript reactjs forms setstate onsubmit


    【解决方案1】:

    handleSubmitfunction 有两个问题。

    preventDefault 中有错字。它需要一个大写字母 D。

    因为你已经用普通声明编写了函数,this 没有被绑定。所以你要么必须自己绑定它

    onSubmit = {this.handleSubmit.bind(this)}
    

    或者更好地将其转换为箭头函数:

    handleSubmit = (event) => {
            event.preventDefault();
    ...
    }
    

    有了这个,函数将被 React 自动绑定。

    【讨论】:

    • 错字.. *箭头函数而不是命名函数。
    猜你喜欢
    • 1970-01-01
    • 2015-02-08
    • 2017-12-15
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 1970-01-01
    相关资源
    最近更新 更多