[英]Ajax call in React Starter Kit
I'm using React Starter Kit to create my first React app, and I'm struggling with Ajax calls. 我正在使用React Starter Kit来创建我的第一个React应用程序,并且我在Ajax调用中苦苦挣扎。 I saw that this Kit embeds a way to perform Ajax calls (which is by the way used internally for app routing):
我看到该工具包嵌入了一种执行Ajax调用的方式(通过内部用于应用程序路由的方式):
import fetch from '../../core/fetch';
I've added this in my component, and then try to perform an Ajax call when the component loads. 我已经在组件中添加了它,然后在组件加载时尝试执行Ajax调用。 Here is my code:
这是我的代码:
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);
}
I'm also using the state value in my render function: 我还在渲染函数中使用状态值:
render() {
var rows = [];
for (var i = 0; i < this.state.modulesList.length; i++) {
rows.push(
<li>{this.state.modulesList[i]}<li/>
);
}
This code put together logs this in my console: 这段代码一起记录在我的控制台中:
Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
Then the Ajax call is performed (successfully) and my console is now showing this: 然后(成功)执行了Ajax调用,我的控制台现在显示以下内容:
Promise
__proto__:Promise
[[PromiseStatus]]:"resolved"
[[PromiseValue]]:Array[16]
The desired behaviour is of course to update my view: when the ajax calls is performed, display one line per array member. 所需的行为当然是更新我的视图:执行ajax调用时,每个数组成员显示一行。
What am I missing? 我想念什么?
Thanks 谢谢
What I suggest doing: 我建议做什么:
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}`);
}
You can't actually return the fetched/parsed data from an async
function. 您实际上无法从
async
函数返回获取/解析的数据。 According to this MDN link , async
function returns a promise
, and not the actual data you'd expect to get after parsing it. 根据此MDN链接 ,
async
函数将返回promise
,而不是解析后希望获得的实际数据。
What happened in your case, was that you were actually trying to receive a returned value from an async
function, inside a regular(sync) function (componentDidMount). 在您的情况下发生的事情是,您实际上正在尝试从常规(sync)函数(componentDidMount)内部的
async
函数接收返回值。 You can either do what I suggested, or use .then()
to use setState
after resolving and parsing the promise, in the actual componentDidMount
function. 您可以执行我建议的操作,也可以在实际的
componentDidMount
函数中使用.then()
在解析并解析了承诺后使用setState
。
I suggest reading about async
functions and Promise
before continuing. 我建议在继续之前阅读有关
async
功能和Promise
。
Best of luck! 祝你好运!
Without testing your code, one problem is that you're incorrectly modifying state
directly . 没有测试代码,一个问题是您直接错误地修改了
state
。 That doesn't trigger a render
and therefore your view is not updated. 这不会触发
render
,因此您的视图不会更新。 Try setState()
instead, like so: 尝试使用
setState()
,如下所示:
<li>{this.setState({modulesList[i]})}<li/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.