Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
DanielGaull opened this issue Jul 20, 2023 · 1 comment
Open

Comments

@DanielGaull
Copy link

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.

@DanielGaull
Copy link
Author

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.

@DanielGaull DanielGaull changed the title Changing Legend onChange does not update component Changing Legend onChange does not update component (temp fix found) Jul 20, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant