項目使用的是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