【问题标题】:Post Request not working with React, Redux and Ducks发布请求不适用于 React、Redux 和 Ducks
【发布时间】:2022-01-07 17:19:24
【问题描述】:

我正在使用 React、TS、Redux 和 Ducks (https://github.com/erikras/ducks-modular-redux) 构建一个应用程序

我已经构建了几个 action 和 reducer。但是我发现 Post 操作存在一些问题。我将在这里留下代码作为示例:

export const getChallenges: ReduxActionCreator = () => async (dispatch, getState) => {
  try {
    const data = await ApiClient.get('/challenges');
    console.log('get', data);
    dispatch({
      type: types.GET_CHALLENGES_SUCCESS,
      payload: data.data,
    });
  } catch (error) {
    console.log(error);
  }
};

export const postChallenges: ReduxActionCreator = (body) => async (dispatch, getState) => {
  try {
    const data = await ApiClient.post('/challenges', body);
    console.log('post', data);
    dispatch({
      type: types.ADD_CHALLENGE_SUCCESS,
      payload: data.data,
    });
  } catch (error) {
    console.log(error);
  }
};

所以,getChallenges 工作正常,我已经在浏览器中呈现它。

由于某种原因,postChallenges 甚至没有在 Redux 开发工具中触发,甚至没有给我一个错误。

我只是这样称呼它:


  const dispatch = useDispatch();

  const handleSubmitForm = () => {
    dispatch(postChallenges(values));
    push(Path.AddMissions);
  };


ApiClient 代码

import axios from 'axios';

export const ApiClient = axios.create({
  baseURL: 'https://thnk.gendesa.genit.com.ar/api/v1/',
  timeout: 20 * 1000,
  headers: {
    'Content-Type': 'application/json',
  },
});

ApiClient.interceptors.response.use(
  (response) => response.data,
  (error) => Promise.reject(error),
);

有什么想法吗?

谢谢!

【问题讨论】:

  • push(Path.AddMissions); 被调用了吗?你能 console.log 记录handleSubmitForm 的内部结构,看看正在运行什么吗?
  • 另外,如果我错了,请原谅我,但你确定你需要做dispatch(postChallenges(values)); 而不仅仅是postChallenges(values)
  • 你能分享你ApiClient代码吗?
  • @TKoL 它被成功调用。不知何故, posyChallenges 没有被调用。如果我控制台记录 postChallenges 函数,它会出现在控制台中。
  • 只是一个旁注:您在这里编写了一种非常过时的 Redux 风格,尤其是结合 TypeScript 将使您编写的代码量是现代 Redux 所需代码量的 4-5 倍。我建议遵循官方的 Redux 教程:redux.js.org/tutorials/essentials/part-1-overview-concepts

标签: javascript reactjs redux httprequest


【解决方案1】:

感谢大家提出的问题和建议。一旦有时间,我一定会检查鸭子文档以改进代码。

关于解决方案,很简单:

只需将挑战减少器添加到商店。

const composeEnhancers = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const rootReducer = combineReducers({
  assesments: assessmentsReducer,
  auth: authReducer,
  events: eventsReducer,
  elements: elementsReducer,
  challenges: challengesReducer,
  questions: questionsReducer,
  surveys: surveysReducer,
  missions: missionsReducer,
});

export const store = createStore(rootReducer, composeEnhancers(applyMiddleware(thunk)));

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

感谢您花时间阅读我的问题

请,

【讨论】:

    猜你喜欢
    • 2019-10-20
    • 2023-01-12
    • 1970-01-01
    • 2019-10-29
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    相关资源
    最近更新 更多