【问题标题】:Clear State After Submit React提交反应后清除状态
【发布时间】:2020-11-11 14:51:30
【问题描述】:

我正在尝试清除以前的状态,无论是单词还是错误,在每次新提交时都有一个值。这可能来自 handleSubmit 函数吗?我尝试通过在提交后将状态设置为空字符串来清除先前的状态,但不幸的是没有奏效。

  state = {
    word:'',
    error: '',
  };


handleChange = (event) => {
this.setState({word:event.target.value.toLowerCase()});
}


handleSubmit = (e) => {
  e.preventDefault();
  this.search(this.state.word)
  this.setState({word: ''});
  this.setState({error: ''});

}


search = async (word) => {

  try{
      const data = await MerriamAPI.getWordInfo(word);
      console.log(data);
      //&& word exists 
      if (data.length && data[0].fl && data[0].meta.stems && data[0].hwi.prs[0].mw && data[0].shortdef[0]){
          console.log('A HERE')
          this.props.handleUpdate({
              word: word,
              info: data,
              versions: data[0].meta.stems,
              shortdef: data[0].shortdef[0],
              partOfSpeech: data[0].fl,
              pronunciation: data[0].hwi.prs[0].mw, 
          });
          this.props.setRedirect({
              path: `/definition/${word}`,
          });
      }
        else {
          console.log('B HERE')
          this.setState({error: 'Word Not Found'});
          console.log(this.state.error)
      }
  }
  catch{
      this.props.setModal('Offline')
  }
}

【问题讨论】:

    标签: reactjs event-handling state submit


    【解决方案1】:

    执行此操作并从句柄提交中删除

    
    this.props.handleUpdate({
      word: word,
      info: data,
      versions: data[0].meta.stems,
      shortdef: data[0].shortdef[0],
      partOfSpeech: data[0].fl,
      pronunciation: data[0].hwi.prs[0].mw,
    });
    this.setState({
      word: ''
    });
    this.setState({
      error: ''
    });
    this.props.setRedirect({
      path: `/definition/${word}`,
    });
    
    

    但是如果这段代码是历史推送,那么你不需要清除状态。请记住,一旦您更改了它们将重新渲染的状态。

    this.props.setRedirect({
      path: `/definition/${word}`,
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-30
      • 2018-08-16
      • 2018-12-30
      • 2022-11-01
      • 1970-01-01
      • 2017-10-20
      • 2020-02-01
      • 1970-01-01
      相关资源
      最近更新 更多