reactjs - redux 发送响应和返回消息
问题描述
在我的操作中,我正在分派类型和有效负载,但如果我还希望将 res.status 和返回 JSON 消息包含到我的道具中怎么办。我将如何在我的 action 和 reducer 中这样做?
行动
export const fetchUserPosts = () => (dispatch) => {
fetch(`${currentPort}/user/recipes`,
{
withCredentials: true,
credentials: 'include',
})
.then((res) => {
if (res.status !== 401) return res.json().then((data) => data);
return { message: { msgBody: 'UnAuthorized' }, msgError: true };
})
.then((posts) => dispatch({
type: FETCH_USER_POSTS,
payload: posts,
}));
};
减速器
export default function (state = initialState, action) {
switch (action.type) {
case FETCH_USER_POSTS:
return {
...state,
fetchUsersPosts: action.payload,
};
default:
return state;
}
}
解决方案
您可以将多个项目组合成一个有效负载。我会为成功和错误创建不同的操作。使用相同的操作会使 reducer 逻辑复杂化。使用 async/await 也比使用嵌套的 Promise 更容易。
这是一个使用SpaceX 开放 API的工作示例:
const FETCH_USER_POSTS_SUCCESS = 'FETCH_USER_POSTS_SUCCESS'
const FETCH_USER_POSTS_FAILED = 'FETCH_USER_POSTS_FAILURE'
const fetchPostSuccessAction = (payload) => ({
type: 'FETCH_USER_POSTS_SUCCESS',
payload,
})
const fetchPostFailureAction = (payload) => ({
type: 'FETCH_USER_POSTS_FAILURE',
payload,
})
const fetchUserPosts = () => async dispatch => {
const res = await fetch('https://api.spacexdata.com/v3/launches/latest');
if (res.status !== 401) {
const { ships: posts } = await res.json();
dispatch(fetchPostSuccessAction({
posts,
status: res.status,
}))
} else {
dispatch(fetchPostFailureAction({
message: { msgBody: 'UnAuthorized' },
}))
}
};
fetchUserPosts()(console.log)
reducer 可以通过解构对象来处理对象,并以您需要的任何方式将属性设置为新状态。您还可以更改其他属性,例如更改errMsg
为true
或false
根据操作的类型:
export default function (state = initialState, { type, payload }) {
switch (type) {
case FETCH_USER_POSTS_SUCCESS: {
const { posts, status } = payload;
return {
...state,
status,
fetchUsersPosts: posts,
msgError: false,
message: null
};
}
case FETCH_USER_POSTS_FAILURE: {
const { message } = payload;
return {
...state,
status: 401,
fetchUsersPosts: null,
msgError: true,
message
};
}
default:
return state;
}
}
推荐阅读
- python - 定位 ID 的最小值和最大值的数据框列
- apache-spark - 将每个 spark 数据框元素与同一数据框的所有其余部分进行比较
- mongodb - pgadmin4 的未完成安装不断阻止其他安装
- javascript - 为什么cypress看不到border *属性的css值?
- php - 替换txt文件中的空格和特殊字符
- java - 从 Jersey 1.x 移动到 Jersey 2.x - NoSuchMethod 错误
- c++ - 如何使用复杂矩阵作为状态类型在 boost odeint 中控制步进误差?
- arrays - 使用循环随机加载字符串数组并添加到datagridview的问题
- github - 使用 Jinja2 进行 GitHub 操作
- r - 使用 lubridate 将持续时间或周期四舍五入到整分钟