[英]Ajax call in React Starter Kit
我正在使用React Starter Kit来创建我的第一个React应用程序,并且我在Ajax调用中苦苦挣扎。 我看到该工具包嵌入了一种执行Ajax调用的方式(通过内部用于应用程序路由的方式):
import fetch from '../../core/fetch';
我已经在组件中添加了它,然后在组件加载时尝试执行Ajax调用。 这是我的代码:
componentDidMount() {
var moduleManager = 'https://my_domain.com/my_endpoint';
async function getModules (url) {
const response = await fetch(url);
const content = await response.json();
return content;
};
this.state.modulesList = getModules(moduleManager);
console.log(this.state.modulesList);
}
我还在渲染函数中使用状态值:
render() {
var rows = [];
for (var i = 0; i < this.state.modulesList.length; i++) {
rows.push(
<li>{this.state.modulesList[i]}<li/>
);
}
这段代码一起记录在我的控制台中:
Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
然后(成功)执行了Ajax调用,我的控制台现在显示以下内容:
Promise
__proto__:Promise
[[PromiseStatus]]:"resolved"
[[PromiseValue]]:Array[16]
所需的行为当然是更新我的视图:执行ajax调用时,每个数组成员显示一行。
我想念什么?
谢谢
我建议做什么:
constructor() {
...
// Bind your async function to your stateful component's class
this.getModules = this.getModules.bind(this);
}
async getModules(url) {
try {
// Perform the ajax call
const response = await fetch(url);
// Convert respone to json
const content = await response.json();
// Process your content (if needed)
...
// Call setState() here
this.setState({someContent: content});
} catch(e) {
console.error(e);
}
}
componentDidMount() {
this.getModules(`${URL}`);
}
您实际上无法从async
函数返回获取/解析的数据。 根据此MDN链接 , async
函数将返回promise
,而不是解析后希望获得的实际数据。
在您的情况下发生的事情是,您实际上正在尝试从常规(sync)函数(componentDidMount)内部的async
函数接收返回值。 您可以执行我建议的操作,也可以在实际的componentDidMount
函数中使用.then()
在解析并解析了承诺后使用setState
。
我建议在继续之前阅读有关async
功能和Promise
。
祝你好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.