我试图使用fetch()来模拟从。/Network获取一些数据。t和不工作。我在控制台得到这个:
Response {type: "basic", url: "csb.app/[object%20Promise]", redirected: false, status: 200, ok: true…}
我组件:
import React, { useState, useEffect } from "react";
import { getOrders} from "./network";
export const Component: React.FC = () => {
const [searchResults, setSearchResults] = useState({});
useEffect(() => {
fetchResults();
},[]);
const fetchResults = async() => {
try {
const data = await fetch(getOrders());
setSearchResults(data);
} catch (e) {
return console.log(e);
}
};
return (
<table className="table table-striped table-hover">
<thead className="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Amount</th>
<th scope="col">ETA</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>{console.log(searchResults)}</tbody>
</table>
);
};
Network.ts
interface Delivery {
id: number;
name: string;
amount: number;
status: string;
eta?: number;
}
export const getOrders = (): Promise<Order[]> => {
return new Promise((resolve) => {
setTimeout(() => {
const data = [
{
id: 1,
name: "Order 1",
amount: 3,
status: "active",
eta: 15
},
{
id: 2,
name: "Order 2",
amount: 5,
status: "pending"
},
{
id: 3,
name: "Order 3",
amount: 3,
status: "active",
eta: 10
},
{
id: 4,
name: "Order 4",
amount: 4,
status: "upcoming"
},
{
id: 5,
name: "Order 5",
amount: 3,
status: "active",
eta: 25
},
{
id: 6,
name: "Order 6",
amount: 3,
status: "active",
eta: 5
}
];
resolve(data);
}, 1000);
});
};
此外,我需要他们渲染他们的状态和上升时间。状态应该按照以下顺序排序:活动、即将到来、待定。
有什么办法吗?
我正在尝试使用fetch()来模拟获取一些数据
你不应该。您在getOrders
中所做的是使用setTimeout
来模拟异步获取一些数据。这很好-但你不需要fetch
!只有当真的发出网络请求以获取数据时才使用fetch
,而不是用于模拟。所以只要把它从你的代码中删除,它就可以工作了:
const fetchResults = async() => {
try {
const data = await getOrders();
// ^^^^^^^^^^^^^^^^^
setSearchResults(data);
} catch (e) {
return console.log(e);
}
};
当你想摆脱模拟时,你应该只改变getOrders
的实现,把fetch()
调用放在里面,取代new Promise((resolve) => {…})
的东西。