如果我在ReactJS或React Native中的类的构造函数中使用setState()函数会发生什么?

Jon*_*ony 51 reactjs react-native

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

constructor(props) {
  super(props);
  this.setState({title: 'new title'});
}
Run Code Online (Sandbox Code Playgroud)

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


我没有读过React中的代码.我恐怕当我这样写时会有任何损害.

swe*_*let 63

什么setState本质上确实是运行了一堆逻辑的你可能不会在构造函数中所需要的.

当你去的时候,state = {foo : "bar"}你只需要为javascript对象分配一些内容state,就像你对任何其他对象一样.(state顺便说一下,这只是每个组件本地的常规对象).

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

  • 如果我在构造函数中有一个promise来处理解析状态会怎么样?我会将promise的回调中的状态设置为`this.setState`吗? (18认同)
  • 如果你需要在构造函数中使用promise - 不要.相反,在`componentDidMount()`中调用promise(例如fetch调用). (3认同)

Ala*_*ong 25

错误消息将是 Uncaught TypeError: Cannot read property 'VARIABLE_NAME' of null

请参阅以下两个jsfiddle代码段.

案例1)工作解决方案jsfiddle

class Hello extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        name: 'world'
      } 
    }

  render() {
    return <div>{this.state.name} </div>
  }
}

ReactDOM.render(<Hello />, document.getElementById('container'));
Run Code Online (Sandbox Code Playgroud)

案例2)不工作的解决方案

class Hello extends React.Component {
    constructor(props) {
      super(props);

      this.setState({
        name: 'hello'
      });
    }

  render() {
    return <div>{this.state.name} </div>
  }
}

ReactDOM.render(<Hello />, document.getElementById('container'));
Run Code Online (Sandbox Code Playgroud)

结论:

我的经验法则,内部直接constructor使用this.state = {},其他地方使用this.setState({ });


小智 5

构造函数:构造函数用于初始化状态。

State:包含本地状态的组件有一个名为“this.state”的属性。

SetState:React 组件有一个可用的方法,称为 setState 调用“this.setState”会导致 React 重新渲染您的应用程序并更新 DOM。您还可以在 setState 中跟踪 prevstate 如果您在构造函数中使用 setState,您会收到类似错误this:只能更新已安装或正在安装的组件。这通常意味着您在未安装的组件上调用了 setState()。