作为mobx存储的Rerender组件已更新 [英] Rerender component as mobx store is updated
问题描述
我正在使用chart.js
实时显示backend
的价格变化.
Backend
更改为frontend
时发送新价格.
priceData
(数组)保存在mobx
priceChartStore
中.
价格更改后,我必须更新chart
.
我使用canvas
标签的ref
值绘制价格图表.
问题是,除非我在render
函数中调用了priceData
值,否则即使在render
函数中未使用priceData
值,也不会调用componentDidUpdate
函数. /p>
它起作用:
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>
);
}
它不起作用:
// render function
render() {
// const {
// priceChartStore: { priceData }, // never used in render function
// } = this.props;
return (
<ChartCanvasWrapper>
<canvas ref={el => (this.el = el)} />
</ChartCanvasWrapper>
);
}
这是mobx
的工作方式还是我的错?
注意:我确定priceChartStore
中没有错误或问题,并将其注入到此component
.
这是mobx
的工作方式(使用 react-mobx)
将组件类或独立的渲染函数转换为反应组件,该组件跟踪渲染使用的可观察对象,并在这些值之一发生更改时自动重新渲染组件.
因此mobx
将仅跟踪render
函数中使用的variables
,并在它们更改时引起重新渲染.
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
.
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.
这篇关于作为mobx存储的Rerender组件已更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!