将数据附加到嵌套的 redux 存储

Append data to the nested redux store

我正在努力在 react-chartjs 中创建一个 Line chart,为此,我会定期从 API 中获取数据,如果成功,我会发送一个更新操作reducer-state。我的 redux 存储中有一个初始数据

var lagData = [{
    options: {
        responsive: true,
        legend: {
            position: 'top'
        },
        title: {
            display: true,
            text: 'ETL lag in minutes'
         },
        scales: {
            xAxes: [{
                type: 'linear',
                position: 'bottom'
            }],
            yAxes: [{
                stacked: true
            }]
        }
    },
    data: {
        labels: [],
        datasets: [
            {
                label: 'Current lag',
                fill: false,
                lineTension: 0.1,
                backgroundColor: "rgba(75,192,192,0.4)",
                borderColor: "rgba(75,192,192,1)",
                borderCapStyle: 'butt',
                borderDash: [],
                borderDashOffset: 0.0,
                borderJoinStyle: 'miter',
                pointBorderColor: "rgba(75,192,192,1)",
                pointBackgroundColor: "#fff",
                pointBorderWidth: 1,
                pointHoverRadius: 5,
                pointHoverBackgroundColor: "rgba(75,192,192,1)",
                pointHoverBorderColor: "rgba(220,220,220,1)",
                pointHoverBorderWidth: 2,
                pointRadius: 1,
                pointHitRadius: 10,
                spanGaps: false,
                data: []
            }
        ]
    }
}]

在这家商店中,我试图将数据附加到 labeldata 标签。但是我不知道怎么做,我正在尝试如下但它不起作用

const lagInfo = (state = lagData, action) => {
    switch(action.type) {
        case 'GET_CURRENT_LAG_RECEIVED': 
            console.log(action.data);
            return Object.assign({}, state, {
                    data: Object.assign({}, state.data.datasets.data, {
                        x: "afsa",
                        y: "fa"
                    })
                });
            break;
        case 'GET_CURRENT_LAG_ERROR':
            console.log(action.err);
            return action.err;
            break;
        default:
            return state;

    }
}

export default lagInfo;

感谢任何帮助

您可以使用 immutability-helper 以不可变的方式更新状态。代码应如下所示:

import update from 'immutability-helper'; //import helper
// ....
case 'GET_CURRENT_LAG_RECEIVED': 
  return update(state, {
    0: {
      data: {
         datasets: {
           0: {
              data: {$push: [{ x: "afsa", y: "fa"}]}
            }
         }
      }
    }
 })
//...

我做了一个 fiddle with an example (there is used deprecated react-addons-update,但它们有相同的行为)。

注意: 你的 lagData 是数组。它不应该是一个对象,因为它是一个状态?在上面的示例中,我假设它应该是 and object,但是如果由于某些原因您仍然必须处理数组 - 这里是 fiddle

PS:更好的是,将状态保持为不可变对象,例如在 this tool 的帮助下。我建议去看看它!