【发布时间】:2018-10-08 08:46:37
【问题描述】:
我需要将 axios 调用中的值分配给它外部的变量。我正在使用 react。
var starthaltname="sdsdsd";
Axios.get('http://localhost:9090/route/getHalt?routeId=3').then(function (starthalt) {
console.log(starthalt.data.name);
return starthalt.data;
}.bind(this));
我可以控制台记录我想要的输出,但是当分配给“starthaltname”变量时,该变量仍然没有定义为值。请问有什么建议吗?
这里是代码的整个渲染部分。我想要的是填充表中的值。
render() {
let table;
let starthaltname;
let endhaltname;
let startdate;
let starttime;
let endtime;
if (this.state.journeylist.length !== 0) {
console.log("data available");
console.log(this.state.journeylist.length);
table = (
<table className="table table-hover table-active">
<tbody>
{this.state.journeylist.map((journey, j) => {
console.log(journey);
var starthaltname="sdsdsd";
Axios.get('http://localhost:9090/route/getHalt?routeId='+journey.busroute+'&haltIndex='+journey.jstartloc).then(function (starthalt) {
console.log(starthalt.data);
console.log(starthalt.data.name);
return starthalt.data;
}.bind(this)).then(function(starthaltresponse){
Axios.get('http://localhost:9090/route/getHalt?routeId='+journey.busroute+'&haltIndex='+journey.jendloc).then(function (endhalt) {
console.log(endhalt.data);
endhaltname=endhalt.data.name;
return endhalt.data;
}.bind(this)).then(function(endhaltresponse){
var sdate = new Date(journey.jstarttime);
startdate = sdate.toDateString();
starttime = sdate.toLocaleTimeString();
var edate = new Date(journey.jendtime);
endtime = edate.toLocaleTimeString();
console.log(starttime);
}.bind(this));
}.bind(this));
console.log(starthaltname);
return (
<tr key={j}>
<td className="text-left" id={journey.journeyId} data-toggle="modal" data-target="#viewTicketModal" >{
<div>
<p className="font-weight-bold text-dark">{startdate}</p>
<hr />
<ul>
<li className="listFrom text-success">{starthaltname}</li>
<p className="lbltime font-italic">{starttime}</p>
</ul>
<ul>
<li className="listFrom text-active">{endhaltname}</li>
<p className="lbltime font-italic">{endtime}</p>
</ul>
<div className="text-right bg-secondary">
<p className="lbljfare text-white">Rs. {journey.jfare}</p>
</div>
</div>
}
</td>
</tr>
);
})}
</tbody>
</table>
);
}
else {
table = "No data available";
}
return (
<div>
{table}
</div>
);
}
【问题讨论】:
-
您没有显示的作业可以正常工作。但是,由于该 API 调用是异步的,您可能已经在 更改它之前记录了
starthaltname。但是,由于您使用的是 React,我将假设您将在您的then()函数中运行this.setState(),这将正常工作。
标签: javascript reactjs promise