为什么我的 React 类没有调用 getInitialState? [英] Why is getInitialState not being called for my React class?

查看:40
本文介绍了为什么我的 React 类没有调用 getInitialState?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Babel 中使用 ES6 类.我有一个如下所示的 React 组件:

import { Component } from 'react';导出默认类 MyReactComponent 扩展组件 {getInitialState() {返回 {富:对,酒吧:'不'};}使成为() {返回 (<div className="theFoo"><span>{this.state.bar}</span>

);}}

看起来没有调用 getInitialState,因为我收到了这个错误:Cannot read property 'bar' of null.

解决方案

开发人员在 v0.13.0 的发行说明.如果您使用扩展 React.Component 的 ES6 类,那么您应该使用 constructor() 而不是 getInitialState:

<块引用>

除了 getInitialState 之外,API 大部分都符合您的预期.我们认为指定类状态的惯用方法是只使用一个简单的实例属性.同样,getDefaultProps 和 propTypes 实际上只是构造函数上的属性.

I'm using ES6 classes with Babel. I have a React component that looks like this:

import { Component } from 'react';

export default class MyReactComponent extends Component {
  getInitialState() {
    return {
      foo: true,
      bar: 'no'
    };
  }

  render() {
    return (
      <div className="theFoo">
        <span>{this.state.bar}</span>
      </div>
    );
  }
}

It doesn't look like getInitialState is being called, because I'm getting this error: Cannot read property 'bar' of null.

解决方案

The developers talk about ES6 class support in the Release Notes for v0.13.0. If you use an ES6 class that extends React.Component, then you should use a constructor() instead of getInitialState:

The API is mostly what you would expect, with the exception of getInitialState. We figured that the idiomatic way to specify class state is to just use a simple instance property. Likewise getDefaultProps and propTypes are really just properties on the constructor.

这篇关于为什么我的 React 类没有调用 getInitialState?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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