gpt4 book ai didi

javascript - ReactJS 因频繁更新大 DOM 而变得迟缓?

转载 作者:搜寻专家 更新时间:2023-11-01 04:54:12 24 4
gpt4 key购买 nike

我们正在考虑将 React 用于 DOM 密集型项目,并希望了解虚拟 DOM 渲染方法的性能特征。

让我担心的一件事是虚拟 DOM 在每个微小的状态变化时都会重新计算。我可以看到这个模型的好处,但是在一个有很多元素和频繁的小更新的应用程序中,这会导致像“悬停”这样简单的东西的大量开销。

例如,这会呈现一系列 N div 并更改 CSS 类 onMouseOver。在我的系统上,它从 N=5000 ( http://jsfiddle.net/estolua/aopvp7zp/ ) 开始变得相当缓慢。

var D = React.DOM;

function generateItems(N) {
return _.map(
_.range(0, N), function (i) { return { id: '_' + i, content: '' + i }; }
);
}

function toggle(x, y) { return (y && x!==y) ? y : null; }

var Item = React.createClass({
render: function () {
var item = this.props.item,
appS = this.props.appState,
focF = this.props.focF;
return D.div({
className: 'item' + (appS.focused === item.id ? ' focused' : ''),
onMouseOver: focF
},
item.content
);
}
});

var App = React.createClass({
getInitialState: function () { return {N: 10, focused: null}; },
changeN: function(e) { this.setState({N: e.target.value}); },
focus: function (id, e) {
this.setState({focused: toggle(this.state.focused, id)});
},
render: function () {
var that = this;
return D.div(null, [
D.div(null, [
D.span(null, 'N: '),
D.input({value: this.state.N, onChange: this.changeN})
]),
D.div(null,
_.map(
generateItems(this.state.N),
function (i) { return React.createElement(Item, {
key: i.id, item: i, appState: that.state, focF: that.focus.bind(null, i.id)
});}
)
)
]);
}
});

React.render(React.createElement(App), document.body);

有没有办法在不放弃漂亮的声明形式的情况下使这些小的更新更有效,或者 React 只是不适合这种规模?

最佳答案

有几个潜在的解决方案可以让您继续使用漂亮的声明式模型:

1。使用 shouldComponentUpdate

当您有很多元素时,shouldComponentUpdate 可以轻松取胜。您评论中的示例不太正确;相反,您想查看您关心的任何 this.props 值是否与您关心的任何 next_props 不同(this 也一样) .statenext_state。例如,要仅在焦点属性更改时重新渲染,您可以这样做:

shouldComponentUpdate: function (next_props, next_state) {
return this.props.appState.focused !== next_props.appState.focused;
},

(尽管这个简单的示例不处理 ID 或处理程序更改)。

虽然这是相当手动的,但您可以轻松构建抽象或混合来比较对象(浅或深,取决于您的 props 的结构)以查看它们是否发生了变化:

var ShallowPropStateCompareMixin = {
shouldComponentUpdate: function(nextProps, nextState) {
return !shallowEquals(nextProps, this.props) ||
!shallowEquals(nextState, this.state);
}
}

var MyComponent = React.createClass({
mixins: [ShallowPropStateCompareMixin],

// ...
});

事实上,这已经实现为the PureRenderMixin .你可以在 this example 中看到这个工作(请注意,其他因素可能会导致大量 DOM 元素运行缓慢,包括影响盒模型的扩展和内联样式)。

2。本地化状态变化

您可以使用的另一种技术是将状态更改本地化;在您的示例中,每次悬停或取消悬停每个项目时,顶级应用程序状态都会发生变化;相反,您可以将此行为委托(delegate)给项目本身(或项目的其他容器)。这样,只有单个容器项目会发生状态变化,而大多数项目根本不会重新呈现。

另一个我没有尝试过的想法是将 n 个项目中的 x 个分组到一个分组组件中(比如,n=5000 和 x=100);然后,只有包含已更改项目的分组组件需要更新。您可以在分组组件上使用 shouldComponentUpdate,这样就不需要迭代其他组件。

关于javascript - ReactJS 因频繁更新大 DOM 而变得迟缓?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27048694/

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