reactjs - React - 如何在第一次渲染之前从存储中获取数组并将其用作 ChartJS 的数据集
问题描述
我已经实现了自己的方法来处理图表标签(React ChartJS 2 库)处的点击事件,它用于过滤数据。我有一个小问题,因为我正在为特定用户存储过滤器的状态,所以首先,当我使用该图表初始化视图时,我必须使用实际过滤器获取数组。问题是即使我得到这个数组,我也不能在我的方法中使用它,因为它总是未定义的。重要的是 - 每次我添加新过滤器时,我也会发送过滤器数组进行存储。我是 React 的新手,所以非常欢迎您的建议。
这是我的代码的一部分(也许 componentDidMount 不是好选择?):
constructor(props) {
super(props);
this.state = {
itemsArray: []
};
}
componentDidMount(): void {
// Overview doughnut chart filtering
AppStore.instance.select(selectQuickQueryParams).pipe(takeUntil(this.componentDestroyed$)).subscribe((quickQueryParam: QueryParamListState) => {
this.setState({itemsArray: quickQueryParam.entities['Connection:NOT IN:connectionType:QuickFiltersComponent'] ? quickQueryParam.entities['Connection:NOT IN:connectionType:QuickFiltersComponent'].value : []})
});
const originalDoughnutLegendBehavior = Chart.defaults.doughnut.legend.onClick;
Chart.defaults.doughnut.legend.onClick = function (e, legendItem) {
if (!legendItem.hidden) {
if (!this.state.itemsArray.includes(legendItem.text)) {
this.state.itemsArray.push(legendItem.text);
}
const query = new QueryParam(EQueryEntity.Connection, 'connectionType', this.itemsArray, EQueryOperator.NotIn, 'QuickFiltersComponent');
AppStore.instance.dispatch(new AddQuickQueryParamsAction([query]));
AppStore.instance.dispatch(new GetUpdateQuickFilters(true));
} else {
if (this.state.itemsArray.length > 1) {
for (let i = this.state.itemsArray.length; i >= 0; i--) {
if (this.state.itemsArray[i] === legendItem.text) {
this.state.itemsArray.splice(i, 1);
break;
}
}
const query = new QueryParam(EQueryEntity.Connection, 'connectionType', this.itemsArray, EQueryOperator.NotIn, 'QuickFiltersComponent');
AppStore.instance.dispatch(new AddQuickQueryParamsAction([query]));
AppStore.instance.dispatch(new GetUpdateQuickFilters(true));
} else {
AppStore.instance.dispatch(new ClearQuickQueryParamsAction());
}
}
originalDoughnutLegendBehavior.call(this, e, legendItem);
};
}
解决方案
您只能使用componentDidMount
方法来获取列表,然后在componentDidUpdate
方法中您可以使用过滤器更新该列表,它将使用最新数据重新呈现您的组件。
推荐阅读
- node.js - 如何在 pg-promise 事务中包装 graphql 请求
- angular - “void”类型上不存在属性“profile”
- node.js - 文件上传适用于邮递员,但不适用于 angular2
- javascript - WordPress AJAX 表单/jQuery 未在后端更新用户元数据
- boost - gdb 从不同位置查找标头
- mysql - creating primary key on two columns which are unique together
- header - 错误要求:Volley 400
- html - Bootstrap 4 columns not working
- dhis-2 - DHIS2 and mysql?
- amazon-web-services - Amazon Cloudfront 和 EC2 重定向设置