繁体   English   中英

我的反应按钮不起作用 - 我使用 useState 和 useEffect

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM