我是 React 的新手,我正在嘗試向我自己的 API 發出 GET 請求,然后在螢屏上呈現結果。當我這樣做時,console.log我的結果也是如此,并且在控制臺中我得到了正確的結果,但我無法將其顯示在我的螢屏上。我是useState用來做這個的。
我的代碼:
const url = "http://localhost:2000/appShop";
const [shop, showShop] = useState("");
const getShop = () => {
Axios.get(url).then((response) => {
console.log(response);
showShop(response.data.name response.data.address response.data.city);
});
};
<Box
sx={{
"& > :not(style)": { m: 1, width: "25ch" },
}}
>
<span>{shop}</span>
<Button onClick={getShop}>List all Shops</Button>
<Button onClick={() => showShopCard(false)}>Close</Button>
</Box>
我得到的結果在這里:

我在控制臺中得到它,但不在我的螢屏上
uj5u.com熱心網友回復:
您的 response.data 是一個陣列。您需要遍歷陣列并將結果保存在狀態中,而且您需要為陣列中的每個元素創建一個跨度項:
const url = "http://localhost:2000/appShop";
const [shop, showShop] = useState("");
const [shopList, setShopList] = useState([]);
const getShop = () => {
Axios.get(url).then((response) => {
console.log(response);
const shopListItems = [];
response.data.forEach(resItem => {
shopListItems.push(resItem.name resItem.address resItem.city)
})
setShopList(shopListItems)
});
};
<Box
sx={{
"& > :not(style)": { m: 1, width: "25ch" },
}}
>
{shopList.map((sl, index) => (<span key={index}>{sl}</span>))}
<Button onClick={getShop}>List all Shops</Button>
<Button onClick={() => showShopCard(false)}>Close</Button>
</Box>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/346215.html
上一篇:如何將字串百分比轉換為浮點小數?
