如果我在 ReactJS 或 React Native 的类的构造函数中使用 setState() 函数会发生什么? [英] What will happen if I use setState() function in constructor of a Class in ReactJS or React Native?

查看:47
本文介绍了如果我在 ReactJS 或 React Native 的类的构造函数中使用 setState() 函数会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于好奇,我只想知道如果我在 React Native 或 ReactJS 的类的构造函数中使用 setState() 函数会发生什么?如:

Out of curiosity, I just wanna know what will happen if I use setState() function in constructor of a Class in React Native or ReactJS? Such as:

constructor(props) {
  super(props);
  this.setState({title: 'new title'});
}

React 的生命周期会发生什么?

what's the lifecycle of React gonna happen?

我还没有阅读 React 中的代码.恐怕我这样写会有些损坏.

I haven't read the code inside React. I am afraid it will some any damage when I write it that way.

推荐答案

setState 的本质是运行一堆你在构造函数中可能不需要的逻辑.

What setState essentially does is to run a bunch of logic you probably don't need in the constructor.

当您使用 state = {foo : "bar"} 时,您只需将某些内容分配给 javascript 对象 state,就像您分配任何其他对象一样.(顺便说一下,这就是 state 的全部内容,只是每个组件本地的常规对象).

When you go state = {foo : "bar"} you simply assign something to the javascript object state, like you would any other object. (That's all state is by the way, just a regular object local to every component).

当您使用 setState() 时,除了分配给对象 state 之外,react 还会重新渲染组件及其所有子组件.您在构造函数中不需要它,因为组件还没有被渲染.

When you use setState(), then apart from assigning to the object state react also rerenders the component and all its children. Which you don't need in the constructor, since the component hasn't been rendered anyway.

这篇关于如果我在 ReactJS 或 React Native 的类的构造函数中使用 setState() 函数会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆