Article From:

Recently, the project is going to react-redux, noting that many projects are also used for redux-thunk; looking at the documentation, we found that it is used for asynchronous operations, but from demo, we really can not see what the effect is, please code friend advice

Answer 0:

After your network request succeeds, dispatch an action based on the data returned, and then react to modify the page. Do you write web without asking for data asynchronously?

for example

export const register = ()=>{
  return (dispatch, getState)=>{
    const {account:{username, password}} = getState();
    //Tell the page registration process to start.Dispatch ({type:types.REGISTER_START}) ('account/register',{username, password},Config).then (resp=> {)If (_2XX (resp.status)) {/ / successful registrationDispatch ({type:types.REGISTER_SUCCESS, payload:'userid'})}}).catch (error=> {)/ / registration failedDispatch ({type:types.REGISTER_FAILED, payload:error.resp)Onse})})}};

Answer 1:

Just read the article of Ruan Yifeng, and come here to discuss it.

First, understand the concept of middleware.

The normal operation is that the view emits the action to the store through dispath, and the reducer receives the action to generate a new state using subscribe to render the view, which is normal synchronization. But when asynchronous operation is required,View issues actions and waits for the asynchronous result to process the reducer, so you need a tool to help you do this, and that’s where the middleware comes in.

Secondly, the asynchronous operation in Redux is analyzed.

reduxThe asynchronous operation sends two actions, one at the beginning of the operation (synchronous at this time) and one at the return of the asynchronous result (asynchronous at this time).

const fetchPosts = postTitle => (dispatch, getState) => {
  // Sending synchronization actionDispatch (requestPosts (postTitle));Return fetch (`/some/API/${postTitle}.json`).tHen (response => response.json ())/ / send asynchronous action.then (JSON => dispatch (receivePosts (POS))TTitle, JSON));};};/ / use method 1Store.dispatch (fetchPosts ('reactjs'));/ / usage twoStore.dispatch (FE)TchPosts ('reactjs')).Then (() =>Console.log (store.getState ()));


The above case can be seen.fetchPosts(reactjs)The return value of a function is still a function.(dispatch, getState)=>{} ,Because dispath can only accept objects, you need the redux-thunk intermediate to handle this function.

Leave a Reply

Your email address will not be published. Required fields are marked *