如何将React.createClass移植到ES6

时间:2017-03-20 01:42:05

标签: reactjs ecmascript-6

我曾经说过

var HomePage = React.createClass({
    getInitialState: function() {  
        var stocks = {};
    ...

feed.onChange(function(stock) {            
            stocks[stock.symbol] = stock;
            this.setState({stocks: stocks, bid: stock, ask: stock, last: stock, type: stock, undsymbol: stock});
        }.bind(this));

        return {
            stocks: stocks
        };
    },  
    componentDidMount() {              
        var props = this.props;
    },
    ...

},

但ES6中没有getInitialState。但是将语句放在constructor

中的位置
return {
                stocks: stocks
       };

它抱怨没有render功能。

class HomePage extends React.Component {
    constructor(props) {
        super(props);
    // Can't do this here
    //  return {
    //       stocks: stocks
    //  };
}

当我执行this.state.stocks[stock.symbol]时,我得到了

app.js:555 Uncaught TypeError: Cannot set property 'JNJ' of undefined
    at n.feed.onChange (<anonymous>:555:45)


componentDidMount() {              
        //var props = this.props;

         feed.onChange((stock) => {            
            this.state.stocks[stock.symbol] =

对如何(放置) return {stocks:stocks}

感到困惑

1 个答案:

答案 0 :(得分:0)

您只需明确设置组件的state属性:

this.state = {
    stocks: stocks
};

在构造函数中。