异步等待redux-thunk

时间:2020-07-05 13:46:41

标签: reactjs redux async-await redux-thunk

我刚开始使用 react-redux ,遇到有关 await 和代码执行顺序的问题。我正在创建一个登录功能,该功能需要Web发送令牌然后获取用户数据。 getToken函数应先执行登录函数,然后根据我的控制台执行。但是,当我检查 Redux Devtools 扩展名时,它说首先执行登录,这会导致错误。我的代码如下:

主要代码:

handleSubmit = async (e) => {
    e.preventDefault();
    let user = {};
    user = {
          name: this.state.name, //this is user-id
          email: this.state.email,
          password: this.state.pass,
        };
      user = JSON.stringify(user);

      await this.props.createAccount(user, this.state.accounttype);
      await this.props.login(this.props.token);//this somehow get executed first
    }
  };

在操作文件夹中:

export const createAccount = (userData, accounttype) => (dispatch) => {
  console.log('create_account');
  let config = {
    headers: {
      'Content-Type': 'application/json',
    },
  };

  console.log(userData);

  axios
    .post(`http://localhost:5000/api/users/${accounttype}`, userData, config)
    .then((res) => {
      dispatch({
        type: CREATE_ACCOUNT,
        payload: res.data.token,
      });
      console.log(res.data);
    })
    .catch((err) => {
      dispatch({
        type: LOGIN_ERROR,
        payload: err,
      });
    });
  console.log('done: create_account');
};

export const login = (token) => (dispatch) => {
  console.log('login');
  if (token) {
    let config = {
      headers: {
        'x-auth-token': token,
      },
    };
    axios
      .get('http://localhost:5000/api/users/me', config)
      .then((res) => {
        dispatch({
          type: LOGIN,
          payload: res.data,
        });
      })
      .then(() => {
        localStorage.setItem('token', this.props.token);
        this.props.history.push(`/`);
        console.log('here alr');
      })
      .catch((err) => {
        console.log('top_login error');
        dispatch({
          type: LOGIN_ERROR,
          payload: err,
        });
      });
  } else {
    console.log('bottom_login error');
    dispatch({
      type: LOGIN_ERROR,
      payload: 'no token detected',
    });
  }

  console.log('done: login');
};

0 个答案:

没有答案