我搜索了这个,但我没有找到任何特定于我需要的东西。如果有的话,请在这里分享。
我正在尝试创建要在各种组件中调用的通用服务。由于它是一个从外部源请求数据的函数,因此我需要将其视为异步函数。问题是,编辑器返回消息“'await' 对该表达式的类型没有影响”。应用程序确实崩溃了,因为还没有数据。
People.js 调用服务 requests.js
import React, { useEffect, useState } from "react";
import requests from "../services/requests";
export default () => {
// State
const [ people, setPeople ] = useState({ count: null, next: null, previous: null, results: [] });
// Tarefas iniciais
useEffect(() => {
carregarpeople(1);
}, []);
// Carregando os dados da API
const carregarpeople = async (pageIndex) => {
const peopleResponse = await requests("people", pageIndex);
// This line below needs to be executed but it crashes the app since I need to populate it with the data from the function requests
// setPeople(peopleResponse);
}
return (
<div>
{
people.results.length > 0 ? (
<ul>
{
people.results.map(person => <li key = { person.name }>{ person.name }</li>)
}
</ul>
) : <div>Loading...</div>
}
</div>
)
}
这是 requests.js,它从 API 返回 json
export default (type, id) => {
console.table([ type, id ]);
fetch(`https://swapi.co/api/${type}/?page=${id}`)
.then(response => response.json())
.then(json => {
console.log(json);
return json;
})}