在React/Redux中,如何post数据遵循JSONAPI结构
In React/Redux, how to post data following JSON API structure
我在 React 中创建了一个表单,我有一个具有 JSON API 结构的 API,即 data: []
[=56= 中的响应].我正在使用 Axios
和 redux-thunk
来获取数据。
来自表单 state
的数据具有以下结构:
{
title: '',
phone: '',
email: '',
description: ''
}
如何使用 axios
、redux-thunk
、action
和 reducer
将其转换为遵循 JSON API 约定:
{
data: [{
title: '',
phone: '',
email: '',
description: ''
}]
}
这就是我卡住的地方:
减速器:
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,
};
}
Thunk:
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
我在 React 中创建了一个表单,我有一个具有 JSON API 结构的 API,即 data: []
[=56= 中的响应].我正在使用 Axios
和 redux-thunk
来获取数据。
来自表单 state
的数据具有以下结构:
{
title: '',
phone: '',
email: '',
description: ''
}
如何使用 axios
、redux-thunk
、action
和 reducer
将其转换为遵循 JSON API 约定:
{
data: [{
title: '',
phone: '',
email: '',
description: ''
}]
}
这就是我卡住的地方:
减速器:
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,
};
}
Thunk:
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