zoukankan      html  css  js  c++  java
  • 记录一次使用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

  • 相关阅读:
    hdu 2176 取(m)石子游戏
    hdu 3549 Flow problem
    hdu 3665 Seaside floyd+超级汇点
    hdu 六度分离 floyd
    hdu 1087 Super Jumping! Jumping! Jumping!
    hdu 1963 Investment 多重背包
    初探数据结构
    Java IO 类一览表
    Java 代码重用:功能与上下文重用
    Java Try-with-resources
  • 原文地址:https://www.cnblogs.com/xiaozhumaopao/p/13817383.html
Copyright © 2011-2022 走看看