[英]my Button in react dosen't work - I use useState and useEffect
我不確定為什么我的 Button 不起作用,我使用 useState 和 useEffect
這是我的代碼:
import React, { useState, useEffect } from "react";
// import Timeout from "await-timeout";
import axios from "axios";
export default function Dogs() {
const [dog, set_Dog] = useState(" ");
console.log({ dog });
useEffect(() => {
async function getFetch() {
const res = await axios.get("https://dog.ceo/api/breeds/image/random");
const {
data: { message },
} = res;
console.log("Got back", message);
set_Dog(message);
}
getFetch();
}, []);
function output() {
set_Dog(dog);
// console.log(set_Dog({ dog }));
}
return (
<div>
<h2>If you like Dogs,{dog} Press Button</h2>
<button onClick={output}>Click me</button>
{dog}
<img src={dog} />
</div>
);
}`
當我點擊按鈕圖像消失時,我想在不刷新瀏覽器的情況下顯示狗的新圖像
在 function output
中設置的dog
的值永遠不會因為過時的關閉而改變。
Because you want to populate the state on mount
and also change it when user clicks on a button, you have to create the function which calls the API in the function scope and memoize it with useCallback
, the same function can be passed to the onClick
. 例如,
export default function Dogs() {
const [dog, set_Dog] = useState("");
console.log({ dog });
const getDogPic = useCallback(async () => {
const res = await axios.get("https://dog.ceo/api/breeds/image/random");
const {
data: { message }
} = res;
console.log("Got back", message);
set_Dog(message);
}, []);
useEffect(() => {
getDogPic();
}, []);
return (
<div>
<h2>If you like Dogs,{dog} Press Button</h2>
<button onClick={getDogPic}>Click me</button>
{dog}
<img src={dog} alt={"dog-pic"} />
</div>
);
}
在代碼沙箱中工作演示
閱讀有關過時關閉的更多信息
獲取第一張圖像后,您可以使用useRef保留對 function 的引用。
const click_ref = React.useRef(null);
useEffect(() => {
async function getFetch() {
const res = await axios.get("https://dog.ceo/api/breeds/image/random");
const {
data: { message },
} = res;
console.log("Got back", message);
set_Dog(message);
}
getFetch();
click_ref.current = getFetch;
}, []);
<button onClick={() => click_ref.current()}>Click me</button>
試試: onClick={() => output()}
就像它只在您單擊按鈕時呈現,而不是在每次組件重新呈現時呈現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.