试图模拟API响应的延迟:无法读取未定义的属性'then'

时间:2017-12-08 19:06:59

标签: javascript reactjs promise mocking es6-promise

在我的React应用程序中,我试图伪造模拟API响应的延迟

  

未捕获的TypeError:无法读取未定义的属性“然后”

createDraft() {
  // Post to Mock API
  const newDraft = {
    name: this.state.draftName,
    created_by: this.props.user,
    created: getDate()
  };

  /* ERROR HERE */
  this.props.create(newDraft).then((res) => {
    console.log(' res', res);
    // Display loading spinner while waiting on Promise

    // Close modal and redirect to Draft Summary view
    this.props.closeModal();
  });
}

行动:

export const create = newDraft => dispatch => all()
  .then(() => setTimeout(() => {
    dispatch({
      type: CREATE,
      newDraft
    });
    return 'Draft created!';
  }, 2000))
  .catch(() => {
    dispatch({
      type: REQUEST_ERROR,
      payload: apiErrors.BAD_REQUEST
    });
  });

连接区域:

const mapDispatchToProps = dispatch => ({
  create: (newDraft) => { dispatch(create(newDraft)); }
});

export const CreateDraftModalJest = CreateDraftModal;

export default connect(cleanMapStateToProps([
  'user'
]), mapDispatchToProps)(CreateDraftModal);

也尝试了同样的结果

function DelayPromise(t) {
  return new Promise(((resolve) => {
    setTimeout(resolve, t);
  }));
}

export const create = newDraft => dispatch => all()
  .then(DelayPromise(2000))
  .then(() => {
    console.log('created called', newDraft);
    dispatch({
      type: CREATE,
      newDraft
    });
  })
  .then(() => 'Draft created!')
  .catch(() => {
    dispatch({
      type: REQUEST_ERROR,
      payload: apiErrors.BAD_REQUEST
    });
  });

1 个答案:

答案 0 :(得分:2)

您的this.props.create()动作创建者可能不会被派遣,因此不会按预期返回承诺。

您正在使用react-redux connect()吗?

编辑:

您的mapDispatchToProps未返回承诺。这样做:

const mapDispatchToProps = dispatch => ({
  create: (newDraft) => dispatch(create(newDraft)),
});