我的问题乍一看似乎微不足道,但我找不到答案,所以也许事实并非如此。基本上我想将 React 用作 DOM 库,不使用状态,即不使用类。我有顶级功能组件,它像往常一样使用 Prop 。我按照 ReactDOM.render 的建议渲染它。然后将在某个地方计算新的 Prop ,我想根据这些新 Prop 重新渲染组件。之前关于 SO 的所有类似问题都有答案,这些答案总是在某处使用 setState
调用来这样做,但在这里我没有类,所以没有 this.setState
可用于我。
我试过的是:
function App(props){
...
}
// using hyperscript here in lieu of jsx
ReactDOM.render(h(App, {..the props..}), document.getElementById('root'));
... later props change, repeat
ReactDOM.render(h(App, {..the props..}), document.getElementById('root'));
我的问题是:如果我这样做,React 是否仍会应用其协调算法来高效更新 DOM?
最佳答案
查看 ReactDOM.render()
的文档:https://reactjs.org/docs/rendering-elements.html我们可以看到以下内容:
React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state.
这通过每秒调用 render()
的示例进行说明:
function tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
ReactDOM.render(element, document.getElementById('root'));
}
setInterval(tick, 1000);
如果你在打开浏览器开发者工具的情况下运行这段代码,你可以看到每次调用 render()
时只有 DOM 的更新部分被更新:
Even though we create an element describing the whole UI tree on every tick, only the text node whose contents has changed gets updated by React DOM.
所以我认为简短的回答是:是的,React 仍然应用协调算法。
此外,根据我自己的经验,我在将 React 组件集成到使用其他框架(例如 Angular)构建的应用程序时使用了类似的模型,并在更新 React 组件时观察到了相同的行为。
关于javascript - React 是否在连续调用 ReactDOM.render 时应用其协调算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54187711/