简体   繁体   中英

How to implement post api calls using thunk middleware in react-redux?

我正在使用 redux-thunk 和 superagent npm 进行 jwt 身份验证,我想知道如何在 actions.js 文件中而不是在主要的 reducer.js 文件中使用 thunk-middleware 实现后期调用

There's a couple of different ways to go about it, but I personally like to use the axios library. Axios essentially just assists with making an API request and parsing the data back from the API into json.

In your actions.js file.

export const authenticateUser = () => {
 return (dispatch, getState) => {
    //get the token from the reducer 
    const jwtToken = getState().jwtTokenReducer.tokenKey
    axios.post("/api/authenticate-user", jwtToken) //jwtToken passed into request
       .then((res) =>){
           dispatch({
              type: "AUTHENTICATE_USER",
              payload: res.data
           })
       }
       .catch((errors) => {
            dispatch({
               type: "ERRORS",
               payload: errors.response.data
            })
        })
 }
}

So take a look at the above syntax. Typically when you define an action-creator, you setup a function that returns an action (object). But thanks to redux-thunk, you can now setup your action-creators to return functions with dispatch as an argument.

So in your returned function you can define certain logic, like making a request to an API like we did up there. Then we can take that data by using the .then promise handler and use it as a payload for an action that we would explicitly dispatch to our reducers.

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