javascript React.render() 回调何时被调用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30642541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When is React.render() callback called?
提问by akula1001
React.render(<MyComponent/>, mainNode, function() {
console.log('2');
});
console.log('1');
prints
印刷
2
1
Also, a scrollTop() in the callback does not work. It works if I call it after render() returns.
此外,回调中的 scrollTop() 不起作用。如果我在 render() 返回后调用它,它会起作用。
Is React.render() synchronous?
React.render() 是同步的吗?
Is the DOM rendered when the function returns?
函数返回时是否渲染了 DOM?
When is the callback called? What would I want to do in the callback?
什么时候调用回调?我想在回调中做什么?
采纳答案by Anthony Blackshaw
You can move the callback logic into the component you are mounting and then use the componentDidMount
method for the first time the component is rendered to the DOM, and componentDidUpdate
for subsequent updates/renders to the DOM. The component will be available in the real DOM via window.document
or using the components getDOMNode
method in both these methods.
您可以将回调逻辑移动到您正在挂载的组件中,然后componentDidMount
在第一次将组件渲染到 DOM 时使用该方法,并componentDidUpdate
在随后的更新/渲染到 DOM 时使用该方法。通过window.document
或使用这getDOMNode
两种方法中的 components方法,该组件将在真实 DOM 中可用。
This is not quite the same as a render callback per se. It's worth noting that if you're changing the state of the component you can also pass a callback function to the setState
method for the component that will be applied once the components state has been updated (and any changes rendered to the DOM).
这与渲染回调本身并不完全相同。值得注意的是,如果您正在更改组件的状态,您还可以将回调函数传递给setState
组件的方法,该函数将在组件状态更新(以及呈现到 DOM 的任何更改)后应用。
Having looked at the React source code to confirm - when rendering a new root node (as per your code snippet) into the DOM the process is synchronous and the callback (if passed) triggers immediately after (https://github.com/facebook/react/blob/master/src/renderers/dom/client/ReactMount.jslines 570-582)
查看 React 源代码以确认 - 当将新的根节点(根据您的代码片段)渲染到 DOM 中时,该过程是同步的,并且回调(如果通过)在(https://github.com/facebook)之后立即触发/react/blob/master/src/renderers/dom/client/ReactMount.js行 570-582)