在React应用程序中更新此Redux存储状态的正确方法是什么

时间:2019-05-13 08:54:07

标签: reactjs redux immutable.js

我有一个使用Redux进行状态管理的React应用。商店的初始结构如下:

const initialState = fromJS({
  visitorRecords: [],
  approvedBookingId: null,
});

在某些时候,我的 visitorRecords 会变成类似以下内容:

[  
   Map {  
      "id":"1556008644569",
      "expectedArrival":"Thu, 25 Apr 2019 08:31:00 GMT",
      "lastName":"Vath",
      "notes":"",
      "actualDeparture":"",
      "actualArrival":"",
      "visitor":"Sven Vath",
      "status":2,
      "cardNumber":2,
      "employeeBeingVisited":"John Doe",
      "firstName":"Sven",
      "expectedDeparture":"Fri, 26 Apr 2019 08:31:00 GMT",
      "verbalStatus":"Visitor returned pass",
      "company":"Disney"
   },
   Map {  
      "id":"1555586876781",
      "expectedArrival":"Thu, 18 Apr 2019 06:30:00 GMT",
      "lastName":"A.",
      "notes":"",
      "actualDeparture":"",
      "actualArrival":"",
      "visitor":"Christoph.",
      "status":0,
      "cardNumber":1,
      "employeeBeingVisited":"Jean Pier",
      "firstName":"Pablo",
      "expectedDeparture":"Sat, 20 Apr 2019 15:30:00 GMT",
      "verbalStatus":"Waiting for visitor arrival",
      "company":"Disney"
   }
]

我要在化简器中执行的操作是通过其ID更新特定记录。我有来自操作的编辑字段的ID和值,但是我不知道如何按照最佳更新做法来处理它们。

这是我的减速器的样子:

export default (state = initialState, action) => {
  switch (action.type) {
    case ON_VISITOR_RECORDS_FETCHED:
      return state.merge({
        visitorRecords: fromJS(action.visitorRecords),
      });
    case ON_RETURN_APPROVED:
      return state.merge({
        approvedBookingId: action.approvedBookingId,
      });
    case ON_VISITOR_RECORD_UPDATED:
      console.log(JSON.stringify(state.get("visitorRecords")));
      // console.log('action.bookingBeingUpdated: ' + action.bookingBeingUpdated)
      // console.log('JSON.stringify(action.updatedTextFields)' + JSON.stringify(action.updatedTextFields))
      // console.log('updatedExpectedArrival: ' + action.updatedExpectedArrival)
      // console.log('updatedExpectedDeparture: ' + action.updatedExpectedDeparture)
      // console.log('updatedStatus: ' + action.updatedStatus)
      return state;
    default:
      return state;
  }
};

在这里,我要使用 action.bookingBeingUpdated ,然后在 visitorRecords 中找到相应的记录,并使用新的 action.updatedTextFields操作进行更新。 UpdatedExpectedArrival,action.updatedExpectedDeparture,action.updatedStatus

我正在阅读this文章,但我不太了解那里的更新是如何发生的。另外,那里的容器的结构也不同。

编辑:visitorRecords内部的元素类型(不是匿名对象,而是地图)

5 个答案:

答案 0 :(得分:1)

通常,您将在vistorRecords数组上使用library(ggplot2) library(ggiraph) obl_year_data <- read.csv("https://raw.githubusercontent.com/savchukidze/data/master/obl_year_data.csv", stringsAsFactors = F) extra_css_bar <- "background-color:#333333;font-family:Ubuntu;font-style:bold;color:white;padding:5pt;" data_css_bar <- "fill:orange;" stat1 <- ggplot(obl_year_data, aes(x = reorder(id, sum), y = sum, tooltip = paste(sum, "млн грн"), data_id = id, fill = obl_year_data$sum))+ geom_hline_interactive(yintercept = 0, size = 0.3, alpha = 1, color = "#333629", linetype = "solid")+ geom_bar_interactive(stat = "identity", alpha = 1, size = 5)+ coord_flip()+ scale_y_continuous(limits = c(0, max(obl_year_data$sum)))+ scale_fill_viridis(option = "D", direction = -1)+ expand_limits(x = -0.1)+ labs(title = "Розподіл субвенцій")+ theme_minimal(base_family = "Ubuntu Medium")+ theme( legend.position = "none", plot.title = element_text(margin = margin(t = 15, b = 15), color = "#14272d", family ="Ubuntu Medium", hjust = 0.5), axis.title = element_blank(), axis.text.y = element_text(color = "black", size = 8.5,debug = T, hjust = 1,margin = margin(0, -10, 0, 0)), panel.grid.major.y = element_blank() ) ggiraph(code = print(stat1), tooltip_extra_css = extra_css_bar, hover_css = data_css_bar, tooltip_offy = 10, selection_type = "none") ,并传递ID和字段以在操作中进行更新,例如,它看起来像这样:

map

答案 1 :(得分:1)

这是使用 immutablejs

的方式
case ON_VISITOR_RECORD_UPDATED:
    const newRecordsCollection = visitorRecords.map(record => {
        if (record.get('id') === action.bookingBeingUpdated) {
            return record.merge({
                updatedTextFields: action.updatedTextFields, 
                updatedExpectedArrival: action.updatedExpectedArrival, 
                updatedExpectedDeparture: action.updatedExpectedDeparture,
                updatedStatus: action.updatedStatus
            });
        }
        return record;
    });

    return state.merge({
        visitorRecords: newRecordsCollection
    });

答案 2 :(得分:0)

您可以像这样更新记录:

case ON_VISITOR_RECORD_UPDATED:
  return {
      ...state, 
      visitorRecords: state.visitorRecords.map(record => {
        if(record.id.toString===action.bookingBeingUpdated.toString()){
          return {
            ...record, 
            updatedExpectedArrival: action.updatedExpectedArrival, 
            updatedExpectedDeparture: action.updatedExpectedDeparture, 
            updatedStatus: action.updatedStatus
          }
        } else {
          return record
        }
      })
    }

答案 3 :(得分:0)

最佳做法是实际execute'", "/usr/share/logstash/logstash-core/lib/logstash/agent.rb:325:in现有状态并返回一个新状态,其中包括您想要的更新后的项目值。

假设您调度了一个动作和一个有效载荷,该有效载荷包括要使用的id和新值:

map()

现在在您的减速器中:

dispatch({
   type: "ON_VISITOR_RECORD_UPDATED"
   payload: newRecordData
})

这可以确保您的reducer具有全新的状态值

答案 4 :(得分:0)

Please don't use state.merge you can use 
```return {
       ...state,
       visitorRecords: [...state.visitorRecords,action.visitorRecords]

}```
Please send Id from action after and compare this id in ON_VISITOR_RECORD_UPDATED type like
```visitorRecords: {
       ...state.visitorRecords,
       data: state.visitorRecords.data.map((items) => {
            if (items.id=== action.id) {
               return { ...items, name: "updated name" };
             }
              return items;
            })
     }```