提交反应后清除状态

时间:2020-07-22 05:58:20

标签: reactjs event-handling state submit

我正在尝试清除以前的状态,无论是单词还是错误,每个新提交都具有值。从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')
  }
}

1 个答案:

答案 0 :(得分: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}`,
});