简体   繁体   中英

REDUX concept queries: 2 ways OR 3 ways to access a redux store. Why use thunk and missing createStore parameters

I am learning about react + redux. I have 3 questions related to it.

query-1: The ways to access a store inside a component. According to the official documentation here there are 2 ways

  1. hooks(useSelector etc.)
  2. connect.

By importing store in our component we can access the store via store.getState() or store.dispatch()

So aren't there 3 ways?

query-2: . We use thunk so that we can do async operations in our action creator(eg API call). The action creator can return a function (instead of an action). Here is a simple example.

    const fetchUser = (data) => {
        return (dispatch) => {
         axios.post('url', data).then(() => { dispatch(action) }).catch();
        }
       }

And we can now dispatch fetchUser from our component(eg: dispatch(fetchUser(payload)) )

Why cannot we simply pass dispatch function to fetchUser instead of using thunk, Here is an example

    const dispatch = useDispatch();
      fetchUser(payload, dispatch)`

Asking because it worked perfectly fine.

query-3 : While creating a redux store, we pass 3 parameters, 1. reducer 2. [preLoadedState] 3. [enhancers]. I have mostly seen examples as shown below

    const store = createStore(rootReducer, applyMiddleware(thunk))

OR

const store = createStore(rootReducer, compose(applyMiddleware(thunk))) 

Since applymiddleware is a store enhancer, we can see we have skipped second parameter. Any thoughts on this?

Q1

As you rightly pointed out there are 2 ways to get Redux State:

  • hooks ( useSelector )
  • connect

store.dispatch or useDispatch is not accessing the Redux State.
Instead it is allowing you to mutate the state of the Store by dispatching actions .

Think of it as:

  • useSelector and connect are subscribers to the Store (they blindly accept changes from the Store)
  • useDispatch and store.Dispatch are prescribers to the Store (actions tell the Store what is changing, and what it's new value will be)

Q2

You can pass the dispatch object around, there's nothing wrong with that (per se), but it could become unclear as to what that object is. In both examples you use, it shows the dispatch object being used to call an action .
Thunk is just used to handle that async behaviour so you don't have to (so much)

Q3

The reason why applymiddleware is called, is because you are then able to pass multiple things into your ReduxStore

For example:

const store = createStore(
  reducer,
  applyMiddleware(promise, thunk)
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM