首页 > 解决方案 > 异步等待未按预期工作:ReactJS

问题描述

我有这个问题,用户必须在成功登录时重定向到相应的仪表板。假设用户在两个配置文件 "p1" 和 "p2" 中有帐户。登录成功后,我正在制作 fetch API 以查看用户是否有相应配置文件的条目。

1)假设如果用户在 p1 中有条目,我需要将他重定向到“p1”仪表板;

2) 如果在 p2 中有条目,则将他重定向到“p2”仪表板。

3)如果p1或p2中都没有条目,则重定向到配置页面,他可以在其中进行一些条目。

4)如果在两个配置文件中,则将要求用户选择相应的仪表板

现在就我而言,我编写的代码没有按预期工作。即使我在“p2”中没有帐户,但在“p1”中有帐户,它也会将我带到配置页面。有人可以帮忙看看这段代码有什么问题吗?

请注意, fetch 调用工作正常!它给了我一系列的项目。如果不存在任何项目,则返回一个空数组

// On login 
  handleLogin = async () => {
        // after successful signin
        await Promise.all([
          this.setDashboard("p1"),
          this.setDashboard("p2"),
        ]);
        this.navigateToDashboards();
  };

   setDashboard = async (profile) => {
    let response, value;
    let type = profile;
    if (type === "p1") {
      response = await this.fetchUserAccounts(type);
      value = !!response && response.length ? true : false;
      this.setState({ isP1: value });
    } else {
      response = await this.fetchUserAccounts(type);
      value = !!response && response.length ? true : false;
      this.setState({ isP2: value });
    }
  };

  fetchUserAccounts = async (type) => {
    try {
      let response = await fetch({
        url: "/fetch/entries",
        method: "POST",
        body: {
          profile: type,
        }
      );
      return response.json();
    } catch (error) {
      console.log(error);
    }
  };


    navigateToDashboards = () => {
    let { isP1, isP2 } = this.state;
    if (isP1 && isP2) {
      // CODE FOR PROMPTING WHICH DASHBOARD TO GO
    } else if (!isP1 && !isP2) {
      this.props.history.push("/configpage"); 
    } else if (isP1) {
      this.props.history.push("/p1dashboard");
    } else if (isP2) {
      this.props.history.push("/p2dashboard");
    }
  };

标签: javascriptreactjsecmascript-6async-awaitreact-router

解决方案


您在上面编写的代码存在一些问题,它们可能比我们在代码片段中看到的更深入——为什么在客户端而不是从服务器发送仪表板类型的逻辑?

方法中也cloudType没有指定setDashboard

我不知道您要达到什么目的,所以我猜-您可能应该fetchUserAccounts在内部使用componentDidMount并将响应保存在状态中。

我在代码中想出了这样的东西TODO:

class X extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      p1: null,
      p2: null,
    };
  }

  async componentDidMount() {
    const [p1, p2] = await Promise.all([
      this.fetchUserAccounts('p1'),
      this.fetchUserAccounts('p1'),
    ]);
    // NOTE: setState has a second parameter, which is a callback – this way you make sure that the state has been updated – read more here:
    // https://reactjs.org/docs/react-component.html#setstate
    this.setState(s => ({ ...s, p1, p2 }), this.navigateToDashboards);
  }

  fetchUserAccounts = async (type) => {
    try {
      let response = await fetch({
        url: "/fetch/entries",
        method: "POST",
        body: {
          profile: type,
        },
      });
      return response.json();
    } catch (error) {
      console.log(error);
    }
  };

  navigateToDashboards = () => {
    const { history } = this.props;
    const { p1, p2 } = this.state;
    // TODO: Implement your logic how you decide 
    if (isP1 && isP2) {
      // CODE FOR PROMPTING WHICH DASHBOARD TO GO
      return;
    }
    if (isP1) return history.push('/p1dashboard');
    if (isP2) return history.push('/p2dashboard');
    return history.push('/configpage');
  }
}

如果这不起作用,至少看看代码结构。有些地方不需要else声明。使用setState. 利用对象/数组解构。您可能还应该根据这些线条阅读 JS 世界中的内容和false内容——或者也许我在这里遗漏了一些东西。true!!response && response.length ? true : false;


推荐阅读