我想使用 React/JavaScript 执行多个获取请求,我进行了以下尝试,该尝试有效:
const fetchAll = async () => {
Promise.all([
await fetch('/api/...'),
await fetch('/api/...')
]).then(links => {
const response1 = links[0];
const response2 = links[1];
timeData = response1.json();
functionData = response2.json();
})
}
Run Code Online (Sandbox Code Playgroud)
但我想这样做,因为这似乎更有用。如果可能的话,我想使用 useEffect 和 useState 并将不同 API 的数据加载到 useState 中的不同数组中。这是一个例子:
const [data, setData] = useState([]);
useEffect(() => {
fetch("/api/..")
.then((response) => response.json())
.then((r) => {
setData(r);
});
}, []);
Run Code Online (Sandbox Code Playgroud)
有没有办法对多个请求执行此操作并将数据保存在不同的数组中,以便我以后可以访问它们?