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

标签 javascript reactjs redux react-redux redux-thunk

我在 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/

相关文章:

javascript - 我可以在 CSS 中的 div 上剪切蒙版文本吗(有或没有 JS 的帮助)?

javascript - 为什么是 !t​​rue ? 'false' : 'true' returning 'true' ?

reactjs - 本地主机上的 Google map JS API : RefererNotAllowedMapError

javascript - Redux 存储在 React 类组件中返回 null 值

reactjs - 如何在 TypeScript 接口(interface)中指定具有多个对象的数组?

javascript - Internet Explorer 不显示元素

javascript - 使用 HTML+JS 在 Canvas 中绘制 3D

html - 绝对位置 `div` 内部位置相对父级 `div` 在 chrome 和边缘消失

reactjs - 如何在react-native中上传带有表单数据的图像或pdf文件?

unit-testing - React-redux : How to write an integration test