【发布时间】:2021-05-24 07:23:27
【问题描述】:
我的任务是为 poc 创建一个前端。我不是前端开发人员,但我选择使用 React JS。 只有一个页面从多个 API 端点获取数据。 API 端点返回一个简单的 json 对象。 我设法让它工作,但是我的代码很难看,我想创建一个函数来处理所有这些,但我似乎无法做到正确。这是我的代码
export default class Dashboard extends React.Component {
constructor(props) {
super(props);
this.state = {
group1: [],
group2: [],
group3: [],
isLoaded: false,
}
}
componentDidMount() {
const group1_url = "http://localhost/api/1"
const group2_url = "http://localhost/api/2"
const group3_url = "http://localhost/api/3"
fetch(group1_url)
.then(res => res.json())
.then(json => {
this.setState({
group1: json,
})
});
fetch(group2_url)
.then(res => res.json())
.then(json => {
this.setState({
group2: json,
})
});
fetch(group3_url)
.then(res => res.json())
.then(json => {
this.setState({
group3: json,
})
});
}
我正在尝试创建这样的函数:
function fetch_data(url, state) {
fetch(url)
.then(res => res.json())
.then(json => {
this.setState({
state: json,
})
});
}
var group1 = fetch_data(group1_url, group1);
到目前为止还没有快乐。如何创建一个函数来获取数据并在 js 中设置状态? 或者,我怎样才能让我的代码看起来更好?或者还有什么我应该使用/研究的东西吗?
【问题讨论】: