ReactJS-每次调用“ setState”时都会调用渲染吗?

本文翻译自:ReactJS - Does render get called any time “setState” is called?

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="
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React 中,`componentDidMount` 生命周期函数只在组件被挂载到 DOM 上调用一次,因此不适合用于每次打开组件都执行的逻辑。如果你需要在每次打开组件都执行一些操作,可以在 `componentDidUpdate` 生命周期函数中实现。 例如,你可以在 `componentDidUpdate` 中检查组件的状态,如果状态发生了改变,就执行你想要的操作。为了避免在首次渲染执行这些操作,你需要在 `componentDidMount` 中设置一个标志,用于表示组件已经被挂载过了。 下面是一个示例代码,展示了如何在每次打开组件都执行某些操作: ```jsx class MyComponent extends React.Component { constructor(props) { super(props); this.state = { mounted: false, data: null }; } componentDidMount() { this.setState({ mounted: true }); this.loadData(); } componentDidUpdate() { if (this.state.mounted) { this.loadData(); } } loadData() { // 发送请求获取数据 fetch('/api/data') .then(response => response.json()) .then(data => this.setState({ data })); } render() { return ( <div> <h1>{this.state.data}</h1> </div> ); } } ``` 在这个示例中,`componentDidMount` 方法中设置了 `mounted` 状态为 `true`,表示组件已经被挂载过了。在 `componentDidUpdate` 方法中,如果 `mounted` 状态为 `true`,就调用 `loadData` 方法重新获取数据。 需要注意的是,每次调用 `setState` 方法都触发组件的更新,因此需要通过一个标志位来避免无限循环更新的问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值