如何在 react-redux 中使用 thunk 中间件实现 post api 调用?

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

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

有几种不同的方法,但我个人喜欢使用 axios 库。 Axios 本质上只是协助发出 API 请求并将数据从 API 解析回 json.

在你的 actions.js 文件中。

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
            })
        })
 }
}

所以看看上面的语法。通常,当您定义动作创建者时,您会设置一个 return 动作(对象)的函数。但是多亏了 redux-thunk,你现在可以将你的 action-creators 设置为 return 函数,并将 dispatch 作为参数。

因此,在您的 returned 函数中,您可以定义某些逻辑,例如向 API 发出请求,就像我们在上面所做的那样。然后我们可以使用 .then promise 处理程序获取该数据,并将其用作我们将显式分派给我们的 reducer 的操作的有效负载。