当 mobx 存储更新时重新渲染组件
Rerender component as mobx store is updated
我正在使用 chart.js
实时显示 backend
的价格变化。
Backend
更改为 frontend
时发送新价格。
priceData
(数组)保存在mobx
priceChartStore
中。
随着价格的变化,我必须更新 chart
。
我使用 canvas
标签的 ref
值来绘制价格图表。
问题 是 componentDidUpdate
函数不会被调用,除非我在 render
函数中调用 priceData
值,即使它未在 render
函数中使用。
有效:
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 中的工作方式(使用 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.
因此 mobx
将仅跟踪 render
函数中使用的 variables
并在它们发生变化时导致 re-render。
我正在使用 chart.js
实时显示 backend
的价格变化。
Backend
更改为 frontend
时发送新价格。
priceData
(数组)保存在mobx
priceChartStore
中。
随着价格的变化,我必须更新 chart
。
我使用 canvas
标签的 ref
值来绘制价格图表。
问题 是 componentDidUpdate
函数不会被调用,除非我在 render
函数中调用 priceData
值,即使它未在 render
函数中使用。
有效:
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 中的工作方式(使用 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.
因此 mobx
将仅跟踪 render
函数中使用的 variables
并在它们发生变化时导致 re-render。