Reactjs 将api返回值分配给React中的状态
您好,我正在尝试调用api将返回的值分配给React中的状态对象,api正在返回值,但这些值没有设置为状态,不理解原因是什么谢谢Reactjs 将api返回值分配给React中的状态,reactjs,Reactjs,您好,我正在尝试调用api将返回的值分配给React中的状态对象,api正在返回值,但这些值没有设置为状态,不理解原因是什么谢谢 handleDDLCommunityChange = event => { let filesFromApi = []; // ["file1", "file2", "file3", "file4"]; fetch('https://localhost:44352/api/files/Community-1') .then((r
handleDDLCommunityChange = event => {
let filesFromApi = []; // ["file1", "file2", "file3", "file4"];
fetch('https://localhost:44352/api/files/Community-1')
.then((response) => {
return response.json();
})
.then(data => {
filesFromApi = data.map(file => { return { value: file, display: file } });
}).catch(error => {
console.log(error);
debugger;
});
console.log(filesFromApi);
this.setState({
files: filesFromApi.map(file => {
return {
fileName: file,
checked: false
};
})
});
};
这是一个很好的例子。异步方法通过回调分派操作,并取消阻止后续代码分支的执行。然后使用回调在异步方法执行完成(成功或失败)时进行操作
由于在fetch调用链的回调之外调用setState
,因此不能保证在fetch调用完成后运行。正如Sudheer在他们的评论中指出的,您应该尝试在fetch链的然后块中设置状态
警告:未测试的代码
handleDDLCommunityChange = event => {
let filesFromApi = []; // ["file1", "file2", "file3", "file4"];
fetch('https://localhost:44352/api/files/Community-1')
.then(response => response.json())
.then(data => {
filesFromApi = data.map(file => ({ value: file, display: file });
this.setState({
files: filesFromApi.map(file => ({
fileName: file,
checked: false
})
})
});
}).catch(error => {
console.log(error);
debugger;
});
};
setState
应位于then
函数内。您的API调用是异步进行的,它将被延迟一点。在can API响应之前,您正在调用设置状态。我也这样做了,但我收到了以下错误,请提供帮助?Uncaught(in promise)SyntaxError:JSON中位于位置0I的意外标记<我得到如下错误:response.JSON(…).map不是function@Abdul:更新了我的代码。尽管如此,代码还没有经过测试。我把它修好了,我的朋友-非常感谢,这都是不同的问题,我调用了不同的api-再次非常感谢。