我的反应按钮不起作用 - 我使用 useState 和 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>

      );

    }`

当我点击按钮图像消失时,我想在不刷新浏览器的情况下显示狗的新图像


jeck猫
浏览 137回答 3
3回答

慕村225694

由于过时的闭包dog,函数中设置的值永远output不会改变。因为您想要填充状态mount并在用户单击按钮时对其进行更改,所以您必须在函数范围内创建调用 API 的函数并用 记忆它useCallback,相同的函数可以传递给onClick. 例如,export default function Dogs() {&nbsp; const [dog, set_Dog] = useState("");&nbsp; console.log({ dog });&nbsp; const getDogPic = useCallback(async () => {&nbsp; &nbsp; const res = await axios.get("https://dog.ceo/api/breeds/image/random");&nbsp; &nbsp; const {&nbsp; &nbsp; &nbsp; data: { message }&nbsp; &nbsp; } = res;&nbsp; &nbsp; console.log("Got back", message);&nbsp; &nbsp; set_Dog(message);&nbsp; }, []);&nbsp; useEffect(() => {&nbsp; &nbsp; getDogPic();&nbsp; }, []);&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <h2>If you like Dogs,{dog} Press Button</h2>&nbsp; &nbsp; &nbsp; <button onClick={getDogPic}>Click me</button>&nbsp; &nbsp; &nbsp; {dog}&nbsp; &nbsp; &nbsp; <img src={dog} alt={"dog-pic"} />&nbsp; &nbsp; </div>&nbsp; );}Codesandbox中的工作演示阅读有关过时关闭的更多信息

四季花海

获取第一张图像后,您可以使用useRef保留对您的函数的引用。const click_ref = React.useRef(null);useEffect(() => {&nbsp; &nbsp; async function getFetch() {&nbsp; &nbsp; &nbsp; const res = await axios.get("https://dog.ceo/api/breeds/image/random");&nbsp; &nbsp; &nbsp; const {&nbsp; &nbsp; &nbsp; &nbsp; data: { message },&nbsp; &nbsp; &nbsp; } = res;&nbsp; &nbsp; &nbsp; console.log("Got back", message);&nbsp; &nbsp; &nbsp; set_Dog(message);&nbsp; &nbsp; }&nbsp; &nbsp; getFetch();&nbsp; &nbsp; click_ref.current = getFetch;&nbsp; }, []);<button onClick={() => click_ref.current()}>Click me</button>

慕容3067478

尝试 :&nbsp;onClick={() => output()}就像它只在您单击按钮时呈现,而不是在每次组件重新呈现时呈现。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript