React/redux:未按预期保存状态 [英] React/redux: Not saving in state as intended

查看:48
本文介绍了React/redux:未按预期保存状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建评论应用.我正在使用json-server来发布请求.我的数据库看起来像这样

I am building a review app. I am using json-server to do post request. My database looks like this

[{
    "id": 5,
    "name": "Tom Cruise",
    "image": "http://placeholder.pics/svg/300x200/000000",
    "title": "Hiring Manager",
    "employeeId": "22222222",
    "funFact": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
    "dateOfJoining": "04/12/2013"
  },
  {
    "id": 6,
    "name": "Julius Caesar",
    "image": "http://placeholder.pics/svg/300x200/fdfdfd",
    "title": "Sales Executive",
    "employeeId": "33333333",
    "funFact": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
    "dateOfJoining": "04/12/2016"
  }
]

这是我的添加操作

//Add Employee
export const addEmployee = employeeData => dispatch => {
  axios
    .post("http://localhost:3004/employees", {
      employeeData,
      headers: { "Content-Type": "application/json" }
    })
    .then(response =>
      dispatch({
        type: ADD_EMPLOYEE,
        payload: response.data.employeeData
      })
    )
    .catch(err => console.log(err));
};

这是我的减速器

case ADD_EMPLOYEE:
  return {
    ...state,
    employees: [action.payload, ...state.employees],
    loading: false
  };

一切正常.问题是这样存储在数据库中的方式

Everything works fine. The problem is the way it is stored in the database which is like this

{
  "employeeData": {
    "name": "Manpreet Sandhu",
    "title": "bootstrap 4",
    "funFact": "cccZCZCZ",
    "image": "CZCZCZC",
    "employeeId": "ZCZCZC",
    "dateOfJoining": "C"
  },
  "headers": {
    "Content-Type": "application/json"
  },
  "id": 7
}

我要删除在每个条目之前添加的"employeeData".

I want to remove "employeeData" added before each entry.

这就是我在行动中得到的

This is what i receive in my action

推荐答案

请参阅 axios文档

  • axios.post(url [,data [,config]])

在您的动作中重击,

//...
axios
    .post("http://localhost:3004/employees", {
      employeeData,
      headers: { "Content-Type": "application/json" }
    })
//...

您已将标头:{"Content-Type":"application/json"} 放入 data 参数

我想,您会做的应该是这样的

I guess, what you would do, should be something like this

//...
axios
  .post("http://localhost:3004/employees",
    employeeData, //data
    { headers: { "Content-Type": "application/json" } } //config
  )

// or
axios({
  method: 'post',
  url: 'http://localhost:3004/employees',
  data: employeeData,
  headers: { "Content-Type": "application/json" }
})
//...

这篇关于React/redux:未按预期保存状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆