转换为es6后,React js getInitialState无法正常工作

时间:2016-02-02 10:26:21

标签: javascript reactjs ecmascript-6

当我将常规反应javascript代码转换为es6时,我在控制台中收到这两个错误:

{assign var="text" value="Hello world!"}
<script>
if (myjsVar == '2') {ldelim}
    alert('{$text|escape:'javascript'}');
    {include file="inc.html"}
{rdelim}
</script>

我想最初将Warning: getInitialState was defined on TopicsList, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead? Uncaught TypeError: Cannot read property 'isTopicClicked' of null 设为false。

isTopicClicked

我正在使用webpack和baber-loader进行编译。

1 个答案:

答案 0 :(得分:7)

在ES2015中编写组件时,

getInitialState未被使用。 使用constructor()代替了。

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = { myState: 1 };
    }
    render() { ... }
}

或根据您可以访问的ES2015的哪个阶段,您可以使用ES7属性初始值设定项

class MyComponent extends React.Component {
    state = { myState: 1};
    render() {}
}