【发布时间】:2018-10-09 17:19:09
【问题描述】:
我已经搜索了几个小时,但似乎找不到答案。请参阅下面的代码。我要求在信息屏幕上使用一些地铁信息。
我正在获取信息,看到 console.log 有效。但是我在使用这个生成的项目时遇到了困难。我想使用收到的数据,以便在下一班火车到达时显示。为此,我尝试使用结果设置状态,以便我可以访问更下方的数据元素。但是,现在我被困在 setState 给我带来了问题。感觉需要绑定函数,但是this.main = this.main.bind(this)不行。
import React from "react";
import { GraphQLClient } from "graphql-request";
class Rutetider extends React.Component {
constructor(props) {
super(props);
this.state = {
stoppestedet: "rutetider lastes ned"
};
async function main() {
const endpoint = "https://api.entur.org/journeyplanner/2.0/index/graphql";
const graphQLClient = new GraphQLClient(endpoint, {
headers: {
ET: "lossfelt-tavle"
}
});
const query = `
{
stopPlace(id: "NSR:StopPlace:58249") {
id
name
estimatedCalls(timeRange: 3600, numberOfDepartures: 20) {
realtime
aimedArrivalTime
aimedDepartureTime
expectedArrivalTime
expectedDepartureTime
actualArrivalTime
actualDepartureTime
cancellation
notices {
text
}
situations {
summary {
value
}
}
date
forBoarding
forAlighting
destinationDisplay {
frontText
}
quay {
id
}
serviceJourney {
journeyPattern {
line {
id
name
transportMode
}
}
}
}
}
}
`;
const data = await graphQLClient.request(query);
console.log(data);
this.setState({ stoppestedet: data.stopPlace.name });
}
main().catch(error => console.error(error));
}
render() {
return (
<div>
rutetider
<div className="grid-container2">
<div>Mot byen</div>
<div>fra byen</div>
<div>{this.state.stoppestedet}</div>
</div>
</div>
);
}
}
export default Rutetider;
【问题讨论】:
-
不清楚你的问题是什么,请澄清一下:setState 给你带来了什么样的问题?
-
main在构造函数内部 - 在类/对象范围内定义它,从componentDidMount调用this.main()... -
@AlekseyBykov 我收到未定义的错误。
-
@xadm 感谢您的建议。我尝试按照您的建议进行操作,将
main的定义移到构造函数之外,然后从componentDidMount 调用它。但是现在我在 Main-function 上得到了这样的错误:SyntaxError /src/rutetider.js: Unexpected token, expected ( (13:17) 11 | } 12 | > 13 | async function main() { | ^ 14 | const endpoint = "https://api.entur.org/journeyplanner/2.0/index/graphql"; 15 | 16 | const graphQLClient = new GraphQLClient(endpoint, { -
@xadm 可能更容易链接到沙箱:codesandbox.io/s/wkq28n5o6l