記錄一次使用react異步不更新數據的問題


項目使用的是react+mobx,簡要如下:

組件代碼:

componentDidMount() {
    this.handleCard();
}
componentWillReceiveProps(nextProps) {
    console.log(nextProps.name, "new");
}
async handleCard() {
    const { initZeroOneCardData, initcommonCardData, name } = this.props;
    await getName();
    console.log(name, "name");
    console.log(this.props.name, "name");
}

mobx文件代碼:

@action
initZeroOneCardData = async () => {
  this.name = await this.getTime();
  console.log(this.name, "change");
};

getTime() {
  return new Promise((resolve) => {
    setTimeout(() => resolve("nihao"), 3000);
  });
}

問題:在mobx中使用異步請求后更改了name的值,但是在頁面組件中:

componentWillReceiveProps 的生命周期中已經更新了該值,但是在 componentDidMount 生命周期的異步await后面

console.log(name, "name"); //沒有更新 還是原來的值 console.log(this.props.name, "name"); //已經更新了,是異步請求之后的值

原因:name 取自 await 之前的 this.props 的值,然后才執行的 await異步請求,所以請求回來,原來的 props 是沒有變化的;

而第二行: this.props.name 取自 await 異步請求之后的 props ,因此可以獲取到最新的props;

componentWillReceiveProps 該生命周期是一只有最新的props


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM