我曾经说过
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}
答案 0 :(得分:0)
您只需明确设置组件的state
属性:
this.state = {
stocks: stocks
};
在构造函数中。