React表单验证仍然会添加值

时间:2017-10-28 00:23:27

标签: reactjs

所以我进行了一些表格验证,我遇到了一个问题。当我第一次加载Web应用程序并尝试添加一个值并使用我的按钮提交时,它不允许我并给出我想要查看的错误。然而,当我添加一个值setState发生然后我的值被推送到UI,我尝试添加另一个空白值,它工作和我的条件逻辑检查空字符串之前没有经历我在做什么错?

 'query_one': function () {

        const { Pool, Client } = require('pg')

        const pool = new Pool({
            user: 'username',
            host: 'host information',
            database: 'database name',
            password: 'password',
            port: 5432,
        })

        pool.query('SELECT * FROM responses', (err, res) => {
            console.log(res.rows[1].answer)
            pool.end()
        })

        this.emit(':tellWithCard', 'test', this.t('SKILL_NAME'), 'test');

    }

3 个答案:

答案 0 :(得分:0)

您正在检查this.state.input但是没有在该代码中的哪个位置设置状态的input值。

尝试在应用程序中添加此内容:

this.setState({ input: 'some value' });

另外,我建议您使用state来定义应用程序UI。因此,不要使用document.getElementById('error')document.getElementById('test').value,而是让UI反映您所在州的内容。

有关详细信息,请参阅此处:https://reactjs.org/docs/forms.html

答案 1 :(得分:0)

而不是直接操纵DOM:

document.getElementById('test').value = '';

您想要使用React:

this.setState({ input: '' });

React的一个很好的基本规则是不要通过element.value = valueelement.style.color = 'red'之类的调用直接操纵DOM。这就是React(& setState)的用途。请在reactjs.org上了解详情。

答案 2 :(得分:0)

在您查找问题的解决方案之前,我注意到您正在直接更新DOM

实施例

document.getElementById('error').style.color = 'red';
document.getElementById('error').innerHTML = 'Please enter something first';
document.getElementById('test').value = '';

除非您有特殊用例或处理外部插件,否则不建议在处理React时使用虚拟DOM进行更新。 https://www.codecademy.com/articles/react-virtual-dom

伪代码样本

constructor(props) {
  this.state = {
    // retain previous states in here removed for example simplicity
    errorString: ''
  }
}    

addItem() {
        let todo = this.state.input;
        let todos = this.state.todos;
        let id = this.state.id;


          if (this.state.input == '') {
            alert("enter a value");
            this.setState({
              errorString: 'Please enter something first'
            });
          }
          else {
            this.setState({
              todos: todos.concat(todo),
              id: id + 1,
              input: '',
            });
          }

      }
    // notice the "error" and "test" id this could be omitted I just added this for your reference since you mentioned those in your example.
    render() {
      return (
       <div>
         {(this.state.errorString !== '') ? <div id="error" style={{color: 'red'}}>{this.state.errorString}</div> : null}
         <input id="test" value={this.state.input} />
       </div>
    }

每次调用setState时,React都会调用带有更新状态的render,这是正在发生的事情的摘要,但是setState背后有很多东西,包括虚拟DOM的参与。

相关问题