【问题标题】:how to get updated state value after updating in a function如何在函数中更新后获取更新的状态值
【发布时间】:2019-08-27 12:57:52
【问题描述】:

我正在尝试获取登录用户详细信息。我需要将数据放入状态并使用相同的状态进行进一步处理,将数据放入状态并使用这些数据需要时间。使用该数据的状态几乎需要 2-3 秒。

如果我们在 3 秒内使用 setTimeOut() 函数,我解决了这个问题,以便我们在这段时间内更新数据。如果我们不使用setTimeOut()并在更新后使用state wright,那么它将提供状态的初始数据。

complete_date = date + ":" + month + ":" + year;

var query = firebase.database().ref('attendence/'+ complete_date +"/").orderByKey();

email_match=false;
entry_time =null,
l_id = null,

query.on("value",(data)=> 
{
  data.forEach(function(childs) 
  {
    l_id = childs.key;
      // __ to check if the user already loged in before.
    var att_query = firebase.database().ref('attendence/'+ complete_date +"/"+ l_id).orderByKey();
    att_query.once("value",(data)=> 
    {
      if(email == data.child('email').val())
      {
        email_match =  true;
        entry_time = data.child('timeEntry').val();
      }
    }); //  
  });  // 

  this.setState({ last_id:l_id });
  this.setState({ emailMatchState:email_match });
  this.setState({alreayLogedState : entry_time});

}); // _____end of query.on("value",(data)=> 

setTimeout(() => 
{
console.log("-----------------------------------");
console.log("already logged :",this.state.alreayLogedState," email match :",this.state.emailMatchState , " result  : ", this.state.result , " last_id :",st.last_id);
console.log("-----------------------------------");
},3000);

我需要在不使用setTimeout() 的情况下使用更新后的状态,以便更快地运行应用程序。

【问题讨论】:

    标签: reactjs react-native setstate


    【解决方案1】:

    setState 的第二个参数是 callback 在所有更新完成后执行

     this.setState({ last_id:l_id }, () => console.log(this.state.last_id))
    

    【讨论】:

      【解决方案2】:

      setState 接受一个可选的第二个参数,该参数在状态对象更新发生后被调用。

      示例:

      let callback = () => {
       // do something
      }
      
      this.setState({
       keyToUpdate: valueToUpdate
      }, callback)
      

      关于使用此回调的补充阅读: https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296?gi=18aa91e88437

      此外,除非在单独的调用之间发生了某些事情,否则这些:

      this.setState({ last_id:l_id });
      this.setState({ emailMatchState:email_match });
      this.setState({alreayLogedState : entry_time});
      

      可以简化为:

      this.setState({ 
       last_id:l_id,
       emailMatchState: email_match, 
       alreayLogedState: entry_time
      }); //optionally add callback
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-01
        • 2021-11-19
        • 2016-08-26
        • 1970-01-01
        • 1970-01-01
        • 2020-01-12
        • 2019-11-15
        • 1970-01-01
        相关资源
        最近更新 更多