Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

javascript - Can I dispatch multiple actions without Redux Thunk middleware?

I read that Redux Thunk is the reliable way to manage asynchronous actions/request. There's nothing much about dispatching actions by other actions.

How about dispatching synchronous actions? I am not sure of thunk approach's performance issues, but can I just dispatch action inside other action creator without defining function inside?

It seems to me that using redux thunk is unnecessary for this need.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Showing and hiding notification does indeed appear to be a good use case for thunks.

David’s answer describes the “default” way of doing several updates in response to something: handle it from different reducers. Most often this is what you want to do.

Sometimes (as with notifications) it can be inconvenient. I describe how you can choose between dispatching one or several actions in my answer to this question.

In case when you do decide to dispatch multiple actions, either just do it sequentially from your components, or use Redux Thunk. Note that if Redux Thunk seems mysterious to you, you should understand what it really is before using it. It only provides benefits in terms of code organization; in reality it’s not any different from running dispatch() two times in a row yourself.

That said, with Redux Thunk dispatching multiple actions looks like this:

function increment() {
  return { type: 'INCREMENT' }
}

function incrementTwice() {
  return dispatch => {
    dispatch(increment())
    dispatch(increment())
  }
}

store.dispatch(increment())
incrementTwice()(store.dispatch) // doesn’t require redux-thunk but looks ugly
store.dispatch(incrementTwice()) // requires redux-thunk but looks nice

Using Redux Thunk will not have any performance issues. It’s just a nice way of calling functions to which you can hand over your dispatch so they can do it as many times as they want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...