我在更新聚合物页面上的视觉效果时遇到问题。我的元素如下所示:
import { html, LitElement, property } from 'lit-element';
import { connect } from 'pwa-helpers/connect-mixin.js';
// These are the shared styles needed by this element.
import { SharedStyles } from '../../styles/shared-styles.js';
// This element is connected to the Redux store.
import { store, RootState } from '../../store.js';
class TFJSItem extends connect(store)(LitElement) {
@property({type: Number})
private _prediction = 0;
static styles = SharedStyles;
protected render() {
console.log(this._prediction);
return html`
<section>
<h2>TFJS</h2>
<p>${this._prediction}</p>
</section>
`;
}
// This is called every time something is updated in the store.
stateChanged(state: RootState) {
console.log(state.network!.prediction);
this._prediction = state.network!.prediction;
}
}
window.customElements.define('tfjs-item', TFJSItem);
我有一个运行1000次迭代的脚本,该脚本向redux发送操作以更新存储在network.prediction
中的数字。但是,在最后一次状态更改发生后,元素中显示的数字仅更新一次。但是,由于我希望这是一个实时编号,因此我希望将所有更改都记录下来。
奇怪的是,第二个console.log()
每次更改都会执行,但是渲染仅被调用一次。
数据来自tfjs培训过程。我想在每次进行新的迭代时更新预测:
import * as tf from '@tensorflow/tfjs';
import * as d from './data';
import * as m from './model';
import { store } from '../store.js';
import { newPrediction } from '../actions/network.js';
export class Training {
model: m.Model;
data: d.Data;
iterations: number;
constructor(model: m.Model, data: d.Data) {
this.model = model;
this.model.model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
this.data = data;
this.iterations = 0;
}
start() {
var this_ = this;
if (this.iterations < 1000) {
this.iterate();
}
}
iterate() {
this.iterations++;
tf.tidy(() => {
const prediction = this.model.model.predict(tf.tensor2d([5], [1, 1]) as tf.Tensor) as tf.Tensor<tf.Rank>;
store.dispatch(newPrediction(prediction));
this.model.model.trainOnBatch(this.data.xs, this.data.ys);
});
}
}
答案 0 :(得分:0)
LitElement批量调用render()
(实际上是整个更新管道)。可以预期,如果您在一个任务中大量更新状态,则只会调用render()
。
通常,更快的渲染实际上不会在屏幕上更频繁地显示任何内容,因为同步功能和微任务都会阻止绘制,因此,无论如何,浏览器只会在所有更新之后绘制屏幕。