Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 在通过调度操作更新状态后,在React with Redux中执行函数?_Reactjs_React Redux_Axios_Es6 Promise_Redux Thunk - Fatal编程技术网

Reactjs 在通过调度操作更新状态后,在React with Redux中执行函数?

Reactjs 在通过调度操作更新状态后,在React with Redux中执行函数?,reactjs,react-redux,axios,es6-promise,redux-thunk,Reactjs,React Redux,Axios,Es6 Promise,Redux Thunk,我正在使用React和Redux和Thunk中间件 在我的应用程序中,我使用Axios与需要承载身份验证的Web Api进行交互。当请求状态为401未授权时,我使用拦截器进行拦截。在本例中,我有一个操作刷新令牌并将其保存在我的Redux存储中 在我的Axios拦截器中,我希望在执行刷新和保存新令牌的Redux操作后立即重新执行未经授权的请求(使用Axios.request(error.config))。我需要在商店中保存新令牌时执行 我的操作应该如何?如果要使用相同的配置重试请求,并且只更改au

我正在使用ReactReduxThunk中间件

在我的应用程序中,我使用Axios与需要承载身份验证的Web Api进行交互。当请求状态为401未授权时,我使用拦截器进行拦截。在本例中,我有一个操作刷新令牌并将其保存在我的Redux存储中

在我的Axios拦截器中,我希望在执行刷新和保存新令牌的Redux操作后立即重新执行未经授权的请求(使用
Axios.request(error.config)
)。我需要在商店中保存新令牌时执行


我的操作应该如何?

如果要使用相同的配置重试请求,并且只更改authToken,则可以尝试以下操作:

const authenticationProvider = (
  store,
  authAction
) => {
  axios.interceptors.response.use(
    response => response, 
    e => setResponseInterceptor(e)
  );
}


const setResponseInterceptor = (e, authAction, store) => {
  if (
    e.config &&
    e.response &&
    e.response.status === 401 &&
    authAction
  ) {
    console.log('401 intercepted', e);
    return store.dispatch(authAction()).then(_ => api.request(e.config));
  }

  return Promise.reject(e);
};
在你的App.js上,你可以调用Redux提供者,像这样调用authProvider

authenticationProvider(reduxStore, () => { 
  /* Re authenticate function */
  // here you should call the auth service again and save the response on redux
  // or call the re-auth action with reduxStore.dispatch( /* ACTION */)
});

谢谢,快乐编码

抱歉@AxelBrei,我不明白你的答案。代码中的authenticationProvider是什么?我能够截获代码为401的响应,并且能够再次运行请求。问题是,请求应该在使用“我的身份验证”操作更新状态后启动。@ChristianCascone AuthenticationProvider只是一个函数名,您可以在其中包装所有逻辑以调用后端并再次尝试身份验证。我在拦截器中所做的是捕获请求错误,因此它不应该在请求之后分派操作。另外,如果需要等待响应,请使用Promise或async/await来处理异步请求。希望能有帮助!