【问题标题】:Set State Based On Previous State根据先前状态设置状态
【发布时间】:2020-07-22 16:10:43
【问题描述】:

我有两个共享错误状态的函数。我需要 componentDidUpdate 函数中的 setState 根据之前的状态更新错误状态。这是因为目前我可以得到 2 个错误状态,这取决于生命周期函数的调用时间。

state = {
  word: this.props.word,
  error: '',
}


async componentDidMount() {
  const word = this.props.match.params.word;
  try{
    const data = await MerriamAPI.getWordInfo(word);
    if (data.length && data[0].fl && data[0].meta.stems && data[0].hwi.prs[0].mw && data[0].shortdef[0]) {
      this.setState({
        word: word,
        error: '',
       })
      }
    else {
      console.log("Error")
      this.setState({error:'Word Not Found'})
    }
  }
  catch {
    this.props.setModal('Offline');
  }
}


async componentDidUpdate() {
  const word = this.props.match.params.word;
  if (word != this.state.word){
    try{
      const data = await MerriamAPI.getWordInfo(word);
      if (data.length && data[0].fl && data[0].meta.stems && data[0].hwi.prs[0].mw && data[0].shortdef[0]) {
        this.setState({
          word: word,
          error: '',
         })
        }
      else {
        // Need to set this based on previous value
        this.setState({error: 'Word Not Found'})
      }
    }
    catch {
      this.props.setModal('Offline');
    }
    }
  }

【问题讨论】:

    标签: reactjs jsx setstate


    【解决方案1】:

    setState 可以通过接收先前状态作为参数的函数回调来调用。

    this.setState((prevState) => ({
       val: prevState.val + 1)
    }));
    

    【讨论】:

      【解决方案2】:

      React docs:

      如何使用取决于当前状态的值更新状态?

      将函数而不是对象传递给 setState 以确保调用始终使用最新版本的状态。

      incrementCount() {
        this.setState((state) => {
          // Important: read `state` instead of `this.state` when updating.
          return {count: state.count + 1}
        });
      }
      

      所以定义一个可以接受状态对象并返回一个新状态对象的方法,然后将它传递给 setState。

      【讨论】:

        猜你喜欢
        • 2017-07-18
        • 2021-03-28
        • 1970-01-01
        • 2019-08-23
        • 1970-01-01
        • 2021-10-31
        • 2020-10-28
        • 2019-10-20
        • 1970-01-01
        相关资源
        最近更新 更多