【问题标题】:Am I using Redux correctly?我是否正确使用 Redux?
【发布时间】:2016-01-24 05:41:04
【问题描述】:

这只是一个问题, 我很想仔细检查我是否做对了。我来自不同框架的年龄,我想在早期避免不良做法。

我正在使用这个样板:https://github.com/erikras/react-redux-universal-hot-example 我正在用 ES7 编写代码。

我创建了: - 1 个减速器:earlyUser.js - 1 个容器:landingPage.js - 1 个组件:registrationForm.js

在landingPage中,我以这种方式包含来自reducer的方法:

从 'redux/modules/earlyUser' 导入 { saveEmail, savePreferences, checkEmailExists };

我声明了一些句柄

 handleSubmitEmail(data) {
    this.props.saveEmail(data);
 }

 handleSubmitPreferences(data) {
    //some data manipulation
    this.props.savePreferences(data);
 }

在 JSX 部分,我只是将处理程序传递给我的组件:

<registrationForm submitEmail= {::this.handleSubmit}   etc... >

现在在组件内部,我将表单提交链接到这个处理程序:

submitEmail() {
    if (this.validateEmail(this.state.email)) {
      this.props.submitEmailHandler(this.state);
    }
  }

现在我的问题是,我应该在哪里附加承诺返回的 .then 和 .catch ? 理想情况下,我想在 component.js 中做类似

this.props.submitEmailHandler(this.state).then( function emailRegisterCallback(){
   // move to next step
}).catch( function errorHandler(error){
  // there was an error
}

正确吗?

另外,在 ES7 中是否有正确的语法来处理 promise?

【问题讨论】:

    标签: redux ecmascript-2016


    【解决方案1】:

    您通常在动作创建器中处理异步方面:

    从async redux example查看此代码:

    function fetchPosts(reddit) {
      return dispatch => {
        dispatch(requestPosts(reddit));
        return fetch(`http://www.reddit.com/r/${reddit}.json`)
          .then(response => response.json())
          .then(json => dispatch(receivePosts(reddit, json)));
      };
    }
    

    当 Promise 解决时,您应该调度另一个操作以使用成功结果或错误更新状态。

    【讨论】:

    • 另请注意,erikras 有他自己的组织方式,我无法评论因为我没有尝试过,但它似乎与 Redux 建议的正常方式不同。
    猜你喜欢
    • 2016-11-13
    • 2014-05-15
    • 2010-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多