【问题标题】:Returning Promise from action creator in React Native using redux-thunk使用 redux-thunk 从 React Native 中的动作创建者返回 Promise
【发布时间】:2017-02-10 03:12:52
【问题描述】:

我有一个从我的 React 组件调用的动作创建器:

// ...
import { connect } from 'react-redux';
// ...
import { submitProfile } from '../actions/index';

// ...

  onSubmit() {
    const profile = {
      name: this.state.name
      // ...
    };

    this.props.submitProfile(profile)
      .then(() => { // I keep getting an error here saying cannot read property 'then' of undefined...
        console.log("Profile submitted. Redirecting to another scene.");
        this.props.navigator.push({ ... });
      });
  }

export default connect(mapStateToProps, { submitProfile })(MyComponent);

动作创建者的定义如下所示。注意我使用的是 redux-thunk 中间件。

export function submitProfile(profile) {
  return dispatch => {
    axios.post(`some_url`, profile)
      .then(response => {
        console.log("Profile submission request was successful!");

        dispatch({ ... }); // dispatch some action

        // this doesn't seem to do anything . . .
        return Promise.resolve();
      })
      .catch(error => {
        console.log(error.response.data.error);
      });
  };
}

我想要做的是调用操作创建者提交配置文件,然后在该请求成功后,将新路由从我的组件推送到导航器中。我只想能够确定发布请求是否成功,以便我可以推送路由;否则,我不会推送任何东西,而是说发生了错误,然后再试一次。

我在网上查了一下,找到了 Promise.resolve(),但它似乎并没有解决我的问题。我知道如果我使用的是 redux-promise 中间件,我可以在调用动作创建者之后执行 .then 。如何使用 redux-thunk 做到这一点?

【问题讨论】:

  • 好的,现在似乎可以工作了。我只需要为 axios.post 请求添加 return 关键字。即:return dispatch => { return axios.post(...); };
  • 您可以回答自己的问题并接受它。也许这会帮助其他人在未来遇到类似的问题。
  • 其实我没有找到解决方案,因为我想在组件中处理一个错误情况,当我调用动作创建者时,结果发现它总是返回一个成功的情况,即使在动作创建者本身执行了一个捕获。也许我需要在动作创建器的 catch 块中返回 Promise.reject 才能使其工作?
  • 你已经用你的thencatch 处理了这个promise。您可以在then 中发送任何必要的导航。
  • 我不能这样做,因为我无法访问那里的导航器。导航器通过 props 传递给组件。

标签: react-native promise redux redux-thunk


【解决方案1】:

将返回定义为 thunk 的函数的返回值。因此,必须从 thunk 中返回 axios 请求,以使事情正常进行。

export function submitProfile(profile) {
  return dispatch => {
    return axios.post(`some_url`, profile) // don't forget the return here
      .then(response => {
        console.log("Profile submission request was successful!");

        dispatch({ ... }); // dispatch some action

        return Promise.resolve();
      })
      .catch(error => {
        console.log(error.response.data.error);
      });
  };
}

【讨论】:

    猜你喜欢
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 2018-05-21
    • 2018-12-28
    • 2019-01-24
    • 2016-10-18
    • 2020-09-12
    相关资源
    最近更新 更多