我有这段代码
VSS.require(["TFS/WorkItemTracking/Services"], function(workItemServices:any) {
workItemServices.WorkItemFormService.getService().then(function (workItemFormSvc:any) {
if(workItemFormSvc.hasActiveWorkItem()) {
workItemFormSvc.getFieldValue(["System.Id"]).then(function(value:any){
wId = value;
console.log("work item id",value);
});
}
else {
console.log("Active work item is NOT available.");
}
});
});
VSS.require(["VSS/Service"], function() {
userId = VSS.getWebContext().user.id;
console.log("inside require::::", VSS.getWebContext().user.id);
});
this.setState({workItemId : wId}, ()=>console.log(this.state.workItemId));
this.setState({personId : userId}, ()=> console.log(this.state.personId));console.log输出如下

红矩形的是this.setState的,绿框的是require的。
我希望有这个值,但是在从require作用域设置值之前,赋值操作就已经完成了。
我怎么能处理这事?
注意:在正式文档中表示require()是异步的
发布于 2020-07-07 13:28:49
我必须在构造函数处绑定函数,然后将this存储为refThis,就在require()块之前
constructor(props:any){
super(props);
this.getIds = this.getIds.bind(this);
}
getIds(){
var refThis = this;
VSS.require(["TFS/WorkItemTracking/Services"], function(workItemServices:any) {
//get workItemId
workItemServices.WorkItemFormService.getService().then(function(workItemFormSvc:any) {
if(workItemFormSvc.hasActiveWorkItem()) {
workItemFormSvc.getFieldValue(["System.Id"]).then(function(value:any){
// Is there a problem with the following line ? (loadData() has to work after id is assigned)
refThis.setState({id:value}, () =>{ refThis.loadData() });
});
}
}));
});
}发布于 2020-07-07 10:04:01
在setState中的console.log之前,您需要使用require()。例如:
VSS.require(["TFS/WorkItemTracking/Services"], function(workItemServices:any) {
workItemServices.WorkItemFormService.getService().then(function (workItemFormSvc:any) {
if(workItemFormSvc.hasActiveWorkItem()) {
workItemFormSvc.getFieldValue(["System.Id"]).then(function(value:any){
wId = value;
this.setState({workItemId : wId}, ()=>console.log(this.state.workItemId));
console.log("work item id",value);
});
}
else {
console.log("Active work item is NOT available.");
}
});
});https://stackoverflow.com/questions/62761284
复制相似问题