在Redux中的bindActionCreators之后无法获得承诺

时间:2016-07-25 15:02:03

标签: promise redux redux-thunk

我使用react / redux创建一个应用程序。

我有一个自定义操作创建器来发出异步请求(我使用redux-thunk)。

export function loginAttempt(userData) {
  return dispatch => {

    let formData = new FormData();
    formData.append('username', userData.username);
    formData.append('password', userData.password);

    fetch('https://api.t411.ch/auth', {
      method: 'POST',
      body: formData
    }).then(response => {
      if (response.status !== 200) {
        const error = new Error(response.statusText);
        error.respone = response;
        dispatch(loginError(error));
        throw error;
      }
      return response.json();
    }).then(data => {
       dispatch(loginSuccess(data));
    });
  }

在我的组件中,我使用bindActionCreators将此方法与dispatch:

绑定
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';


import SearchBar from './SearchBar';
import TorrentLayout from './TorrentLayout';

import * as LoginActions from '../actions/login'; // <---- it's where the code above is located
import * as SearchActions from '../actions/search'; 


function mapStateToProps(state) {
  return {
    login: state.login,
    searching: state.searching
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({...LoginActions, ...SearchActions}, dispatch);
}

@connect(mapStateToProps, mapDispatchToProps)
export default class Home extends Component {

  constructor(props) {
    super(props);

    console.log('should be a promise');
    let foobar = this.props.loginAttempt({username: 'username', password:'password'});

    console.log(foobar); // <------ undefined

    // that I want to do
    this.props.loginAttempt({username: 'username', password:'password'}).then(() => {
        this.props.search(this.props.login.token, "mysearch");
    }
  }

  render() {
    return (
      <div>
        <div>
           <SearchBar {...this.props} />
           <TorrentLayout {...this.props}/>
        </div>
      </div>
    );
  }
}

我想申请&#39;然后&#39;我的动作创作者已经开始派遣。

谢谢

2 个答案:

答案 0 :(得分:1)

您需要在return fetch()内的箭头功能内loginAttempt。像这样:

export function loginAttempt(userData) {
  return dispatch => {
    return fetch('https://api.t411.ch/auth', {
      method: 'POST',
      body: formData
    }).then(...);
  }

基本上,当您调用绑定的动作创建者时,箭头函数会被执行,但它没有返回值。

答案 1 :(得分:0)

对我来说,我在调度器内部完成所有的逻辑,所以我传递给它一个完成的回调。

在我的组件中,我按如下方式调用操作登录

           1
         1 2
       1 2 3
     1 2 3 4
   1 2 3 4 5
 1 2 3 4 5 6

然后在我的操作中,我执行所有异步调用,然后在最后调用 done(data)

login(values, setErrors, (user) => {
    console.log('done:', user)
})
相关问题