为什么我要使用 Redux Promise 中间件而不是 Redux Promise?

Why would I use Redux Promise Middleware over Redux Promise?

我用过 Redux Promise, but it seems Redux Promise Middleware 有更多的功能,比如调度多个附加了 "PENDING" 或 "FULFILLED" 的动作。

为什么我要用一个而不是另一个?

我个人更喜欢 Redux Promise Middleware 作为中间件,因为它支持乐观更新;调度未决、已完成和已拒绝的操作;并与 Redux Thunk 一起很好地链接异步操作。

例如,您可以在减速器中使用 _PENDING_FULFILLED 的操作,并使用进度条和类似的更新 UI。

Redux Pomise 中间件有一个替代品。 Redux Auto 与 redux-promise-middleware 具有相同的 API,并在底层提供了一系列实用模式以减少您需要编写的样板文件。

我们的想法是每个 action in a specific file。将服务器调用与"pending"、"fulfilled" 和"rejected" 的reducer 函数放在一起。这使得处理承诺变得非常容易。

它还会自动将 helper object (called "async") 附加到您的状态原型,允许您跟踪 UI,请求转换。

示例:

data/serverThing.js

export function pending (posts, payload){
  return posts
}

export function fulfilled (posts, payload, result){
  return result.serverResponse
}

export function rejected (posts, payload, error){
  return posts;
}

export function action (payload) {
  return Promise.resolve({serverResponse: [1,2,3,4]})
}

UI

import React  from "react"
import actions from 'redux-auto'
import { connect } from 'react-redux'

class Foobar extends Component {

  const currentLoadingData = this.props.data.async.serverThing;

  if(currentLoadingData instanceof Error){
    var data = currentLoadingData.message
  } else if(true === currentLoadingData ){
    var data = "Loading..."
  } else {
    var data = this.porps.data.join();
  }

  render () {
    return (
      <div>
        <button onClick={()=>actions.data.serverThing()}>Do something!</button> 
        { data }
      </div>
    )
  }
}

const mapStateToProps = ( { data }) => {
  return { data }
};

export default connect( mapStateToProps )(Foobar);

To understand the above source. redux-auto automatically creates actions and wires them to reduces based on the file structure. Where the folder name becomes the name of the property on the state. The files within a folder are actions to be performed on that part of the state.

这里是完整的redux-auto: helloworld project