React JS从多个API函数中获取数据



我的任务是为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状态?或者,我如何使我的代码看起来更好?或者还有什么我应该使用/调查的?

传递字符串作为第二个参数,并使用computed属性:

function fetch_data(url, state) {
fetch(url)
.then(res => res.json())
.then(json => {
this.setState({
[state]: json,
})
});
}
fetch_data(group1_url, 'group1');

我还强烈建议捕获错误——应该尽可能避免可能的未处理的拒绝。

您可能希望使用Promise.all等待所有组加载:

const dataSources = {
group1: 'http://localhost/api/1',
group2: 'http://localhost/api/2',
group3: 'http://localhost/api/3',
};
Promise.all(
Object.entries(dataSources).map(([propertyName, url]) => (
fetch(url)
.then(res => res.json())
.then((result) => {
this.setState({
[propertyName]: result
})
})
))
)
.then(() => {
this.setState({ isLoaded: true })
})
.catch((error) => {
// handle errors
})

(还请注意,您的json参数不是JSON - JSON只是与字符串一起存在的格式。被反序列化的东西只是一个普通的对象或数组。最好叫一个不那么容易误导人的名字,就像我那样叫result)

你可以试试Promise.all

的承诺。All接受一个promise数组(技术上它可以是任何可迭代对象,但通常是一个数组),并返回一个新的promise。

const points = [
"http://localhost/api/1",
"http://localhost/api/2",
"http://localhost/api/3",
];
const responses = await Promise.all(points.map((point) => fetch(point)));
const data = await Promise.all(responses.map((response) => response.json()));
const [group1, group2, group3] = data;
this.setState({
group1,
group2,
group3,
});

请记住将此逻辑包装在async函数

你可以这样做。

function fetch_data(url, state) {
fetch(url)
.then(res => res.json())
.then(json => {
this.setState({
[state]: json,
})
});
}
var group1 = fetch_data(group1_url, 'group1');

最新更新