我的应用存在问题,因为当我单击新按钮功能时,它会重新渲染一次新笑话。这是我的代码:
import React, { useState, useEffect } from "react";
import { Typography, Button } from "@material-ui/core";
import Navigation from "../Navigation";
export default function RandomJoke() {
const [isLoaded, setLoaded] = useState(false);
const [jokeData, setJokeData] = useState({});
const [loadNewJoke, setLoadNewJoke] = useState(false);
function useFetch() {
async function fetchMyAPI() {
let response = await fetch("https://icanhazdadjoke.com/slack");
response = await response.json();
setJokeData(response);
setLoaded(true);
}
useEffect(() => {
fetchMyAPI();
if (loadNewJoke) setLoadNewJoke(false);
}, [loadNewJoke]);
}
useFetch();
function reloadJoke() {
setLoaded(false);
setLoadNewJoke(true);
}
return (
<>
<Navigation mainpage="RandomJoke" />
<Typography variant="h6">Random Dad Joke</Typography>
{isLoaded && <div>{jokeData.attachments[0].text}</div>}
{!isLoaded && <div>loading...</div>}
{isLoaded && (
<Button variant="contained" onClick={() => reloadJoke()}>
New one
</Button>
)}
</>
);
}
我尝试添加一个新玩笑状态挂钩,但仍然无法解决。谢谢
最佳答案
每当loadNewJoke
的值更改时,都会触发useEffect,对吗?不只是当loadNewJoke
设置为true时。仔细查看按下按钮后发出的呼叫以及setLoadNewJoke
的呼叫次数。