gpt4 book ai didi

javascript - mobx 存储更新时重新渲染组件

转载 作者:行者123 更新时间:2023-12-02 23:24:32 24 4
gpt4 key购买 nike

我正在使用 chart.js 实时显示后端的价格变化。Backend 在更改为 frontend 时发送新价格。priceData(数组)保存在mobx priceChartStore中。随着价格的变化,我必须更新图表。我使用 canvas 标签的 ref 值来绘制价格图表。

问题是,除非我在 render 函数中调用该 priceData 值,否则不会调用 componentDidUpdate 函数,即使它没有在 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 中没有任何错误或问题,并将其注入(inject)到此组件中。

最佳答案

这是 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 函数中使用的变量,并在它们发生更改时导致重新渲染。

关于javascript - mobx 存储更新时重新渲染组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56797827/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com