简体   繁体   English

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

[英]In React/Redux, how to post data following JSON API structure

I created a form in React and I have a API that has a JSON API structure, ie with the response inside the data: [] property. 我在React中创建了一个表单,我有一个具有JSON API结构的API,即在data: []属性中包含响应。 And I'm using Axios and redux-thunk to fetch the data. 而且我正在使用Axiosredux-thunk来获取数据。

The data coming from the form state has this structure: 来自表单state的数据具有以下结构:

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

How do I convert it so it follows the JSON API convention, using axios , redux-thunk , action and reducer : 如何使用axiosredux-thunkactionreducer redux-thunk ,使其遵循JSON API约定:

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

This is where I'm stuck: 这就是我遇到的问题:

Reducer : 减速机

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

    default:
      return state;
  }
}

Actions : 动作

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);
        }
      });
  };
}

I'm not sure where and what to do to format a new data into the JSON API structure. 我不确定在何处以及如何将新数据格式化为JSON API结构。

Not 100% sure, but I think here: 不确定100%,但我在这里认为:

return axios.post( apiUrl )

You're not actually sending any data. 您实际上并没有发送任何数据。 I reckon you want to do: 我认为您想这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM