React中的异步功能无法访问此功能

时间:2018-04-08 05:01:15

标签: reactjs

我在Apollo Client上使用React。当用户登录时,我需要重新获取USER查询,以便我可以根据其配置文件中存在的字段来决定将它们重定向到何处。

我的代码挂在这一行:

await this.props.USER.refetch();

我认为这是因为使异步函数改变了this的上下文。

async login() {

  const result = await this.props.LoginMutation({
    variables: {
      email: this.state.email,
      password: this.state.password,
    },
  });

  const token = await result.data.authenticateUser.token;

  await this._saveUserData(token);

  // This is where the code hangs 
  await this.props.USER.refetch();


  // If no user profile pic has been set then redirect to the account page
  if (!this.props.USER.user.profilePic) {
    this.setState({
      redirect: '/account',
    });
  }

  // If no location is set redirect to the homepage
  if (!this.props.USER.user.location) {
    this.setState({
      redirect: '/',
    });
  }

  if (this.props.USER.user.location) {
    this.setState({
      redirect: `/${this.props.USER.user.location.machineName}`,
    });
  }

  this.setState({
    redirect: `/`,
  });
}

React dev工具向我显示this.props.USER.refetch()确实存在:

enter image description here

1 个答案:

答案 0 :(得分:1)

它不是因为函数实现不同的上下文的异步,而是因为ES6类中的函数需要显式绑定。使用像

这样的箭头功能
login = async () => {

  const result = await this.props.LoginMutation({
    variables: {
      email: this.state.email,
      password: this.state.password,
    },
  });

  const token = await result.data.authenticateUser.token;

  await this._saveUserData(token);

  // This is where the code hangs 
  await this.props.USER.refetch();


  // If no user profile pic has been set then redirect to the account page
  if (!this.props.USER.user.profilePic) {
    this.setState({
      redirect: '/account',
    });
  }

  // If no location is set redirect to the homepage
  if (!this.props.USER.user.location) {
    this.setState({
      redirect: '/',
    });
  }

  if (this.props.USER.user.location) {
    this.setState({
      redirect: `/${this.props.USER.user.location.machineName}`,
    });
  }

  this.setState({
    redirect: `/`,
  });
}