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



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

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

在您的操作中.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
            })
        })
 }
}

所以看看上面的语法。通常,在定义操作创建者时,会设置一个返回操作(对象(的函数。但是多亏了 redux-thunk,您现在可以设置您的动作创建者以返回带有 dispatch 作为参数的函数。

因此,在返回的函数中,您可以定义某些逻辑,例如像我们在那里所做的那样向 API 发出请求。然后,我们可以使用 .then promise 处理程序获取该数据,并将其用作我们将显式调度到化简器的操作的有效负载。

最新更新