【问题标题】:Correct pattern for async dispatch异步调度的正确模式
【发布时间】:2017-11-17 14:55:01
【问题描述】:

请帮助我,使用 redux thunk 进行异步调度是否正确?

//actions types
const ADD_ARTIST = 'ADD_ARTIST'

// action
function AddArtist(val){
  return {
    type: ADD_ARTIST,
    payload:val
  }
}


//some async events 
function async1(id){
  return fetch(.....)
}

function async2(id){
  return fetch(.....)
}

function async3(id){
  return fetch(.....)
}

function auth(id) {
  return function (dispatch) {
    async1(10).then( (v) =>  dispatch(AddArtist(v)) );
    Promise.all([
      async2(26),
      async3(51),
    ]).then(
          (v) => dispatch(AddArtist(v[0] + v[1] )
      ));
  }
}


var ViewWrapper = connect(
  state => ({
    playlist: state.playlist,
    artist: state.artist,
  }),
  dispatch => (
    {
      dispatch,
      auth: bindActionCreators(auth, dispatch)
  })

)(View);

和按钮:

  <input type='button' onClick={() => 
this.props.dispatch( this.props.auth() ) }   value='dispatch mapDispatch>>>>>>>' />

【问题讨论】:

  • 根据documentation,这看起来是正确的。但你也需要错误处理。

标签: redux redux-thunk


【解决方案1】:

根据redux documentation,这看起来不错,但您还应用了一些代码来处理错误。

在这里你可以写出更好的方式

function auth(id) {
     return ((dispatch) => async1(10)
               ).then( (v) => dispatch(AddArtist(v))
               ).then( () => 
                 Promise.all([
                    async2(26),
                    async3(51),
               ])
              ).then( (v) => dispatch(AddArtist(v[0] + v[1])) 
             )
      )
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    相关资源
    最近更新 更多