如何有效地在可编辑表中使用redux saga

问题描述 投票:2回答:1

我有一个多页面反应应用程序,其中一个端点必须以表格形式显示数据。显示我对该端点的GET_INFO采取componentWillMount行动。现在我有一个名为table_info的减速器,里面有table_data数组和shouldTableUpdate布尔值。

我的表格可编辑,每行都有editdelete图标。我在update面临问题,在update我称呼减速机与行动UPDATE_TABLE_ROW如果成功比我做的事情如下:

//reducer.js

const initialState = {
    table_data:{}, shouldTableUpdate:false;
}
export default function myReducer(state=initialState, action){
    switch(action.type){
        case UPDATE_SUCCESS:
            // how to handle edited row here?
            // also when I print my state of this reducer
            // state becomes nested, so if one does lots of updates
            // it will be become very heavy... 
            return {...state, shouldTableUpdate:true}
    }
}

你能告诉我如何有效地使用redux saga处理更新,删除,添加表吗?在谷歌搜索我只得到天真的例子,所以来到SO。

注意:无法显示我公司项目的实际代码。对不起。

谢谢。

reactjs react-redux redux-saga
1个回答
0
投票

你能告诉我如何有效地使用redux saga处理更新,删除,添加表吗?

那么你可以使用减速器明显地操纵state对象。

评论:

  1. table_data是一个列表,而不是一个对象。
  2. 我不认为你需要shouldTableUpdate,因为如果在mapStateToProps中映射状态字段,则存储中的状态更改将触发组件更新。

所以这是通过reducer添加,更新和删除项目的基本模板。

const initialState = {
  table_data: [],
};

export default function myReducer(state=initialState, action){
  switch(action.type) {
    case ADD_ITEM:
      return {
        ...state,
        table_data: [
          ...state.table_data,
          action.item, // item to be added
        ]
      };
    case UPDATE_ITEM: 
      let updatedItem = action.item;
      // do something with updatedItem
      return {
        ...state,
        table_data: table_data.map(e => (
          e.id === updatedItem.id ? updatedItem : e
        )),
      };
    case DELETE_ITEM:
      const index = state.table_data.findIndex(e => e.id === action.item.id);
      const numItems = state.table_data.length;
      return {
        ...state,
        table_data: [
          // exclude index
          ...table_data.slice(0, index),
          ...table_data.slice(index+1, numItems),
        ]
      };
    default:
      return state;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.