Does React re-render all components and sub components every time setState
is called?
(每当调用setState
React是否会重新渲染所有组件和子组件?)
If so, why?
(如果是这样,为什么?)
I thought the idea was that React only rendered as little as needed - when state changed.(我以为这个想法是,当状态改变时,React只渲染所需的内容。)
In the following simple example, both classes render again when the text is clicked, despite the fact that the state doesn't change on subsequent clicks, as the onClick handler always sets the state
to the same value:
(在下面的简单示例中,尽管状态在以后的单击中不会改变,但两个类在单击文本时都再次呈现,因为onClick处理程序始终将state
设置为相同的值:)
this.setState({'test':'me'});
I would've expected that renders would only happen if state
data had changed.
(我曾希望只有在state
数据已更改的情况state
才会进行渲染。)
Here's the code of the example, as a JS Fiddle , and embedded snippet:
(这是示例代码,例如JS Fiddle和嵌入式代码段:)
var TimeInChild = React.createClass({ render: function() { var t = new Date().getTime(); return ( <p>Time in child:{t}</p> ); } }); var Main = React.createClass({ onTest: function() { this.setState({'test':'me'}); }, render: function() { var currentTime = new Date().getTime(); return ( <div onClick={this.onTest}> <p>Time in main:{currentTime}</p> <p>Click me to update time</p> <TimeInChild/> </div> ); } }); ReactDOM.render(<Main/>, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
[1]: http://jsfiddle.net/fp2tncmb/2/
ask by Brad Parks translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…