alibaba / BizCharts

Powerful data visualization library based on G2 and React.

Home Page:http://bizcharts.net/products/bizCharts

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Changing Legend onChange does not update component (temp fix found)

DanielGaull opened this issue · comments

BizCharts Version: 4.1.22
Platform: MacOS

Editing Legend properties such as visible and position will update immediately, but changing the onChange event handler does not. I cannot use forceUpdate on the Chart because it freezes the page. Example:

const onLegendChange = useCallback(event => {
   // do stuff...
}, [dependency]);

return (
   <Chart
      {...chartProps}
   >
      <Legend onChange={onLegendChange} />
      {children}
   </Chart>
);

When dependency changes, the onLegendChange function is updated. However, clicking items in the legend will still have the old behavior until the chart is manually re-rendered through some other means.

Ok, so I've found the problematic section of code. This is in components/Legend/index.tsx:

// 事件didmount后绑定一次即可
  useEffect(() => {
    // 连续图例
    view.on('legend:valuechanged',(ev: {
      /** [ start, end ] */
      originValue: [ number | any,  number | any ],
      /** [ start, end ] */
      value: [  number | any,  number | any ],
    }) => {
      if (_isFunction(props.onChange)) {
        props.onChange(ev, view)
      }
    });
    // 分类图例
    view.on('legend-item:click', (ev: IEvent) => {
      if (_isFunction(props.onChange)) {
        const { target } = ev;
        const delegateObject = target.get('delegateObject');
        const { item } = delegateObject; // 图例选项
        ev.item = item; // 快捷获取
        props.onChange(ev, view);
      }
    });
  }, []);

The empty dependency array for this useEffect means it will only run on the first render. When props.onChange changes, the chart event is not updated.

There is a fix. When you load the chart, you can get the g2Instance (a prop on Chart) and call .on yourself (the g2Instance is the 'view' referenced above) to re-register the legend click events when they change.

I'm leaving this issue open since this does not follow the expected behavior. If you run into this issue, the fix above should work.