问题
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 priceData
value 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