我在react中创建了一个表单,并且我的API具有JSON API结构,即具有data: []
属性内的响应。我正在使用Axios
和redux-thunk
获取数据。
来自表单state
的数据具有以下结构:
{
title: '',
phone: '',
email: '',
description: ''
}
我如何转换它,因此使用axios
,redux-thunk
,action
和reducer
:
{
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,
};
}
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