使用kriasoft/react-starter-kit创建web应用程序。它从我的api服务器获取对象,并在页面上显示它们。在获取数据时,应用程序应该显示一个加载图标。
我的代码在获取对象后不会重新呈现组件。它继续显示“正在加载...”,即使我希望看到“数据已加载!”。
import React from 'react';
import fetch from 'isomorphic-fetch'
class Search extends React.Component {
constructor(...args) {
super(...args);
this.getObjectsFromApiAsync = this.getObjectsFromApiAsync.bind(this);
this.state = {
isLoading: true,
};
}
async getObjectsFromApiAsync() {
try {
const response = await fetch('http://localhost:3030/api');
const content = await response.json();
// console.log(content)
this.setState({isLoading: false});
} catch(e) {
console.error(e);
}
}
componentWillMount() {
this.getObjectsFromApiAsync();
};
render() {
if (this.state.isLoading) {
return (
<p>Loading...</p>
);
}
return (
<p>Data loaded!!</p>
);
}
}
发布于 2018-01-15 13:32:07
通过在我的api服务器上添加res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');解决了这个问题。问题不在反应中。
https://stackoverflow.com/questions/48224124
复制相似问题