我正在Line chart
中创建react-chartjs
,因为我定期从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: []
}
]
}
}]
在此商店中,我尝试将数据附加到label
和data
标记。但我无法弄清楚如何,我正在尝试如下,但它不起作用
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;
感谢任何帮助
答案 0 :(得分:1)
您可以使用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(使用了已弃用的react-addons-update
,但它们具有相同的行为)。
注意:您的lagData
是阵列。不应该是一个对象,因为它是一个状态?在上面的示例中,我假设它应该是对象,但如果由于某些原因,您仍然需要处理数组 - 这里是fiddle。
PS :更好的是,将您的状态保持为不可变对象,例如在this tool的帮助下。我建议你去做吧!