我试图从js文件到我的jsx文件中获取数组我该怎么办?
这是我的js文件,httpservice.js:
var urlArray = [];
var request = require('request');
request.post(
'http://thecatapi.com/api/images/get?format=xml&results_per_page=10&type=gif',
{ form: { key: 'value' } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
var parseString = require('xml2js').parseString;
var xml = body;
parseString(xml, function (err, result) {
var responsObj = result.response;
var dataArrayObj = responsObj.data;
var dataObj = dataArrayObj[0];
var imagesArray = dataObj.images;
var imageObj = imagesArray[0];
var imageArray = imageObj.image;
for (var i = 0; i < imageArray.length; i++) {
var object = imageArray[i];
var url = object.url[0];
urlArray.push(url);
console.log("almoss " + url);
}
});
}
});
var service ={
get:function(){
console.log("making request");
return urlArray;
}
};
这是我的jsx文件,gifurllist.jsx:
var React = require('react');
var GifItem = require('./GifItem.jsx');
var Http = require('../services/httpservice');
var List = React.createClass({
getInitialState: function(){
return {urlarray:[]};
},
componentWillMount: function(){
Http.get().then(function(data){
console.log("data:" + data);
this.setState({urlarray: data});
}.bind(this));
},
render: function(){
var listItems = this.state.urlarray.map(function(item){
return <GifItem key={item.id} url={item.url} />;
});
return(<ul> {listItems}</ul>);
}
});
module.exports = List;
在行Http.get()。然后(函数(数据)我想在数据中获取我的urlArray .. 我怎样才能做到这一点?
答案 0 :(得分:0)
你可以尝试不在componentWillMount中使用then方法并使用如下:
componentWillMount: function(){
var data = Http.get(); //this is not returning a promise
//so then may not be used
console.log("data:" + data);
this.setState({urlarray: data});
}