reactjs 如何从setState的回调中从外部函数返回?

pb3s4cty  于 2022-12-03  发布在  React
关注(0)|答案(1)|浏览(135)

实现这一目标的最佳方法是什么?

const func = (newPermissions) => {
  this.setState({
    permissions: { ...newPermissions }
  },
  () => {
    if (this.state.permissions.read) {
      // If we get here then func should return the result of an api call
      // Currently the return just returns from callback of setState and func returns nothing
      return api.getInfo().then((response) => {
        return response;
      });
    }
  });
}

我尝试直接从回调返回,但它只是从setState的回调返回,而函数没有返回任何内容。

更新:潜在解决方案

这是一个潜在的解决方案吗?

const func = (newPermissions) => {
  return new Promise(resolve => {
    this.setState({
      permissions: { ...newPermissions }
    },
    () => {
      if (this.state.permissions.read) {
        resolve(api.getInfo().then((response) => {
          return response;
        }));
      }
    });
  });
}
h43kikqp

h43kikqp1#

没有别的办法,只能用承诺

const func = (newPermissions) => {
  return new Promise(resolve => {
    this.setState({
      permissions: { ...newPermissions }
    },
    () => {
      if (this.state.permissions.read) {
        return api.getInfo().then((response) => {
          resolve(response);
        });
      }
    });
  });
}

或另一个回调

const func = (newPermissions, callback) => {
  this.setState({
    permissions: { ...newPermissions }
  },
  () => {
    if (this.state.permissions.read) {
      return api.getInfo().then((response) => {
        callback(response);
      });
    }
  });
}

相关问题