Rerender component as mobx store is updated

让人想犯罪 __ 提交于 2019-12-24 21:01:38

问题


I am using chart.js to show price changes from the backend in real time. Backend sends a new price when it is changed to frontend. priceData(array) is saved in mobx priceChartStore. I have to update chart as price is changed. I use ref value of canvas tag to draw price chart.

The problem is that the componentDidUpdate function is not called unless I call that priceDatavalue in render function,even though It isn't used in render function.

It works:

componentDidUpdate() {
  const { priceChartStore: { priceData } = this.props;
...
// update chart
  this.chart = new LineChart({
      el: this.el,
      priceData,
      config: {
      liveMode: true,
      startTime,
      endTime,
      maxDataLength: MAX_PRICES_LENGTH,
      },
  });
...
}
// render function
render() {
    const {
        priceChartStore: { priceData }, // never used in render function
    } = this.props;
    return (
        <ChartCanvasWrapper>
            <canvas ref={el => (this.el = el)} />
        </ChartCanvasWrapper>
    );
}

it doesn't work:


// render function
render() {
    // const {
    //     priceChartStore: { priceData }, // never used in render function
    // } = this.props;
    return (
        <ChartCanvasWrapper>
            <canvas ref={el => (this.el = el)} />
        </ChartCanvasWrapper>
    );
}

Is this the way mobx works or is it my fault?

Note: I am sure that there's no bug or issue in priceChartStore and injecting it to this component.


回答1:


This is the way mobx works in react (with react-mobx)

React component class or stand-alone render function into a reactive component, which tracks which observables are used by render and automatically re-renders the component when one of these values changes.

So mobx will tracks only the variables used in the render function and cause re-render when they change.



来源:https://stackoverflow.com/questions/56797827/rerender-component-as-mobx-store-is-updated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!