代码之家  ›  专栏  ›  技术社区  ›  cubefox

setState的异步返回值

  •  2
  • cubefox  · 技术社区  · 7 年前

    我想做到以下几点:

    myFunction = () => {
      this.setState(
        state => {
          const originalBar = state.bar;
          return {
            foo: "bar"
          };
        },
        () => ({ originalBar, newBar: state.foo }) //return this object
      );
    };
    
    otherFunction = () => {
      var originalValue = myFunction(); //access returned object (in child component)
    };
    

    setState不返回任何内容,我唯一能想到的方法就是调用回调函数 my function 然而,在setState回调中,如果可能的话,我更喜欢使用async wait来实现这一点。

    3 回复  |  直到 7 年前
        1
  •  3
  •   Tholle    7 年前

    你可以退一个新的 Promise 从…起 myFunction setState .

    然后你可以用 async / await 在你的 otherFunction .

    myFunction = () => {
      return new Promise(resolve => {
        let originalFoo;
        this.setState(
          state => {
            originalFoo = state.foo;
            return {
              foo: "bar"
            };
          },
          () => resolve({ originalFoo, newFoo: this.state.foo })
        );
      });
    };
    
    otherFunction = async () => {
      var originalValue = await myFunction();
    };
    
        2
  •  0
  •   user1063295 user1063295    7 年前

    我下面的实现不使用async/await。如果你需要等到 setState 如果完成了,你最好还是接受Thole的答案。但是,如果您只想返回一个具有值的对象,而不管状态是否已完全设置,那么我的方法就更简单了。

    myFunction = () => {
      let returnData;
      this.setState(state => {
        // do some stuff here
        returnData = { originalBar, newBar: state.foo };
        return {
          foo: "bar"
        };
      });
    
      return returnData;
    }
    
    otherFunction = () => {
      var originalValue = this.myFunction();
    }
    

    但是,我不建议这样做,相反,我会尽量不在中使用函数回调 this.setState

    const originalBar = this.state.foo; // or whatever it might be
    const newBar = "bar";
    this.setState({ foo: newBar });
    return { originalBar, newBar };
    

    比较短,比较优雅。

        3
  •  0
  •   Hemant Parashar    7 年前

    看起来您想要访问上一个状态和当前状态。而不是使用 setState 要做一些不打算做的事情,您可以在react中使用生命周期方法,它根据您的用例为您提供以前的状态和以前的道具。

    componentDidUpdate(prevProps, prevState, snapshot){
      ...
    }
    

    getSnapshotBeforeUpdate(prevProps, prevState){
    ...
    }