新的反应,已经看到了一些类似的标题如下,但仍然无法澄清错误进入控制台说Uncaught TypeError: this.state.stock.map is not a function
。当我在另一个api调用中使用类似的代码时,就不会出现这样的错误。代码如下所示。如果我从get方法中分配数据来存储它也不起作用并给出相同的问题。问题是什么 ?我提到的一些链接。
var StockData = React.createClass({
getInitialState: function() {
return {
stock: []
};
},
componentDidMount: function() {
this.serverRequest = $.get(this.props.source, function (data) {
var old = JSON.stringify(data).replace("//", ""); //convert to JSON string
var obj = JSON.parse(old); //convert back to JSON
console.log(obj);
this.setState({
stock: obj
});
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
return (
React.createElement("div",null,
React.createElement("ul",null,
this.state.stock.map(function (listValue){
return React.createElement("li",null,listValue.t,"( ",listValue.e," )-"," Current Price :",listValue.l_cur," Date :",listValue.lt
);
})
)
)
);
}
});
ReactDOM.render(React.createElement(StockData, { source: "http://www.google.com/finance/info?q=NSE:ATULAUTO,WIPRO,INFY" }),document.getElementById('proper-list-render3'));
答案 0 :(得分:0)
将渲染函数替换为自身
render: function() {
var self = this;
return (
React.createElement("div",null,
React.createElement("ul",null,
self.state.stock.map(function (listValue){
return React.createElement("li",null,listValue.t,"( ",listValue.e," )-"," Current Price :",listValue.l_cur," Date :",listValue.lt
);
})
)
)
);
}
答案 1 :(得分:0)
我终于得到了问题的解决方案。调用url后收到的数据以字符串格式接收,而不是JSON。正确的代码如下,现在它正常工作。谢谢@ Piyush.kapoor的帮助。
componentDidMount: function() {
this.serverRequest = $.get(this.props.source, function (data) {
var old = data.replace("//", "");
this.setState({
stock: JSON.parse(old)
});
}.bind(this));
}