【发布时间】: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