gpt4 book ai didi

javascript - 在 React/Redux 中,如何按照 JSON API 结构发布数据

转载 作者:行者123 更新时间:2023-12-01 03:06:12 25 4
gpt4 key购买 nike

我在 React 中创建了一个表单,并且有一个具有 JSON API 结构的 API,即在 data: [] 属性内包含响应。我使用 Axiosredux-thunk 来获取数据。

来自state表单的数据具有以下结构:

{
title: '',
phone: '',
email: '',
description: ''
}

如何使用 axiosredux-thunkactionreducer 对其进行转换,使其遵循 JSON API 约定:

{
data: [{
title: '',
phone: '',
email: '',
description: ''
}]
}

这就是我陷入困境的地方:

reducer :

export default function roleReducer(state = [], action) {
switch(action.type) {
case types.SAVE_ROLE_SUCCESS:
return [
...state,
Object.assign({}, action.role)
];

default:
return state;
}
}

操作:

export function saveRoleSuccess(role) {
return {
type: types.SAVE_ROLE_SUCCESS,
role,
};
}

重击:

export function saveRole(role) {
return (dispatch, getState) => {
return axios.post(apiUrl, role)
.then(savedRole => {
console.log('Role: ', savedRole);
dispatch(saveRoleSuccess(savedRole));
console.log('Get state: ', getState());
})
.catch(error => {
if (error) {
console.log('Oops! Role not saved.', error);
}
});
};
}

我不确定在哪里以及如何将新数据格式化为 JSON API 结构。

最佳答案

不是100%确定,但我认为:

return axios.post( apiUrl )

您实际上并没有发送任何数据。我想你想做的是:

const dataToPost = { data: [ role ] }; //wrap the role in an array and an object
return axios.post( apiUrl, dataToPost ); //send the data

关于javascript - 在 React/Redux 中,如何按照 JSON API 结构发布数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46162519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com