首页 > 解决方案 > 将项目添加到数据库后更新 Redux 状态

问题描述

我还是个新手。我正在尝试构建一个小型全栈应用程序来跟踪项目中的时间。

我有一个带有 Postgresql 数据库的 Ruby on Rails API 和一个带有 Redux、Redux-React 和 Redux-thunk 的 React 前端,用于状态管理。所有 CRUD 功能在前端和后端之间都可以正常工作,但我无法在任何操作后更新 Redux 状态。

我的初始状态


{data: Array(2), included: Array(6)}
    data: Array(7)
      0:
        attributes: {done: false, date: "2021-01-08", name: "Test3", customer: "Test3", sum_hours: 0}
        id: "69"
        relationships: {tasks: {…}}
        type: "project"
        __proto__: Object
      1: {id: "70", type: "project", attributes: {…}, relationships: {…}}
      2: {id: "71", type: "project", attributes: {…}, relationships: {…}}
      3: {id: "72", type: "project", attributes: {…}, relationships: {…}}
      4: {id: "73", type: "project", attributes: {…}, relationships: {…}}
      5: {id: "1", type: "project", attributes: {…}, relationships: {…}}
      6: {id: "5", type: "project", attributes: {…}, relationships: {…}}
length: 7
__proto__: Array(0)
included: (6) [{…}, {…}, {…}, {…}, {…}, {…}]
__proto__: Object

这在成功 POST 到 db 后从动作传到我的减速器

{type: "ADD_NEW", data: {…}}
  data:
    attributes: {done: false, date: "2021-01-08", name: "Testi1", customer: "Testi1", sum_hours: 0}
    id: "74"
    relationships: {tasks: {…}}
    type: "project"
    __proto__: Object
    type: "ADD_NEW"
    __proto__: Object

我的减速机

const ProjectReducer = (state = [], action) => {
    switch (action.type) {
        case 'ADD_NEW':             
            return Object.assign({}, state.data,
                {
                    attributes: action.attributes,
                    id: action.id,
                    relationships: action.relationships
                })        
        case 'DEL_PRO':             
            return state.data.filter(st => st.id != action.id)
        case 'INIT_PROJECTS':
            return action       
        default:
            return state
    }
}

export default ProjectReducer

我在我的减速器 ADD_NEW 上尝试了很多东西,你现在看到的只是最新的,无法更新状态。即使 DEL_PRO 也不起作用,当我在应用程序上发送我的删除时,它只是完全失去了状态。非常感谢所有帮助!

标签: reactjsreduxreact-reduxredux-thunk

解决方案


我认为 state.data 是一个数组,所以你应该这样做:

case 'ADD_NEW': 
  return {
    ...state,
    data: state.data.concat({
      attributes: action.attributes,
      id: action.id,
      relationships: action.relationships,
    }),
  }

推荐阅读