當我按下按鈕時,我希望 API 中的地址顯示在按鈕下方的螢屏上。
我必須把它寫在Next.js,但我不知道該怎么做。

import axios from 'axios';
import React, { useEffect, useState } from 'react';
import { Button } from '@material-ui/core';
function TestPage() {
console.log(process.env.NEXT_PUBLIC_WECODE_URI);
const [state, setState] = useState('');
const customFetch = async () => {
const results = await axios
.get(`${process.env.NEXT_PUBLIC_WECODE_URI}/testapi`)
.then((res) => res.data?.results[0]?.address);
setState(results);
};
useEffect(() => {
customFetch();
}, []);
return (
<>
<Button
variant="contained"
color="primary"
style={{ width: '200px' }}
onClick={() => customFetch}>
address
</Button>
</>
);
}
export default TestPage;
uj5u.com熱心網友回復:
您想在獲得結果后設定狀態。在.then()你的愛可信呼叫不起任何作用,因為不回傳該資訊-這是一個簡單的回呼,其中您可以在處理結果,但因為你正在使用async和await,結果被傳遞回你將其分配給變數。
const customFetch = async () => {
const result = await axios.get(`${process.env.NEXT_PUBLIC_WECODE_URI}/testapi`);
// If you want to set the state to the address
setState(result.data?.results[0]?.address)
// If you want to set the state to the full result
setState(result)
}
請注意,useEffect()由于依賴項陣列為空,您會在組件的掛載和卸載上運行[]。這意味著該customFetch函式將在安裝和卸載組件時運行。我認為這不是您想要的功能,因為您為此提供了一個按鈕,因此useEffect可以將其洗掉。
您還想顯示資訊。為此,您可以像這樣使用狀態...
return (
<>
<Button
variant="contained"
color="primary"
style={{ width: '200px' }}
onClick={() => customFetch}>
address
</Button>
<p>{state}</p>
</>
);
uj5u.com熱心網友回復:
您應該在 .then(res => setState(res.data ...)) 中呼叫 setState 并在您的組件中放置“狀態”以顯示地址。實際上你不需要將 axios 存盤在變數中。只需在函式中呼叫 axios 并在“then block”中呼叫 setState 并將結果存盤在 state 中。在這種情況下,您想通過按鈕獲取地址,您不需要在 useEffect 中呼叫 customFetch()。但是如果你想在頁面啟動時獲取地址,你可以像這樣使用useEffect鉤子。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/396982.html
上一篇:無法從函式讀取回傳的資料
