简体   繁体   English

清除空输入中的数据-React.js

[英]Clear data on empty input - React.js

I'm trying to find a way to check whether my input is cleared in order to clear data. 我试图找到一种方法来检查是否清除了我的输入以清除数据。

The logic i'm using for this check is if (searchTerm.length === 0) clear input... I've also tried if (searchTerm === '') but they don't work. 我用于此检查的逻辑是if (searchTerm.length === 0)清除输入...我也尝试过if (searchTerm === '')但它们不起作用。 The thing with these logic checks is that the event fires with when the input is cleared and 1 character is added where the length of the string is 0 when it should be 1? 这些逻辑检查的作用是,当清除输入并在字符串长度为0时应添加1个字符(应为1)时触发该事件?

When I console.log my input string length I get 0 for 1 character, 1 for 2 characters and when I completely clear the input I get 1 for 0 characters. 当我CONSOLE.LOG我的输入字符串的长度,我得到0为1个字符, 1 2个字符,当我彻底清除输入我得到1 0个字符。

What is the proper way to check for a cleared input value? 检查已清除的输入值的正确方法是什么?

Here is my logic: 这是我的逻辑:

class SearchBar extends Component {
  state = {
    searchTerm: '',
    error: null
  }

  handleChange = e => {
    const { searchTerm } = this.state

    this.setState({ searchTerm: e.target.value })

    if (searchTerm.trim() === '') {
      this.props.resetSearch()
    }
  }

  render() {
    const { searchTerm, error } = this.state

    return (
      <div className="input-container">
        { error && <p className="invalid">Please Enter Something</p> }
        <input 
          type="text"
          placeholder="search for a repo..."
          value={searchTerm}
          onChange={e => this.handleChange(e)}
          onKeyPress={e => e.key === 'Enter' && this.findRepos(e)}
        />
        <button 
          type="submit" 
          onClick={e => this.findRepos(e)}>
          Search
        </button>
      </div>
    )
  }
}

export default connect(null, { fetchRepos, resetSearch })(SearchBar)
handleChange = e => {
  const { searchTerm } = this.state

  this.setState({ searchTerm: e.target.value })

  if (searchTerm.trim() === '') {
    this.props.resetSearch()
  }
}

You are checking the previous state, not the current input value. 您正在检查以前的状态,而不是当前输入值。 Your code should be 您的代码应为

handleChange = e => {
  const searchTerm = e.target.value;

  this.setState({ searchTerm: searchTerm })

  if (searchTerm.trim() === '') {
    this.props.resetSearch()
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM