react 会render两次,当调用异步方法后?

问题描述:

当button点击一次,render执行了两次?为什么

import { useState, useEffect } from "react";
import "./styles.css";
import axios from "axios";

const App = () => {
  const [count, setCount] = useState(10);

  function axiosAsync() {
    return new Promise((resolve, reject) => {
      axios
        .get("https://api.ydl.com/api/test-category/all", {
          params: {},
          timeout: 10000
        })
        .then((res) => {
          const { data } = res;
          resolve(data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

  async function getData() {
    try {
      const result = await axiosAsync();
      console.log(result, 1);
      setCount(count + 1);
    } catch (e) {
      alert(e);
    }
  }

// 当button点击一次,render执行了两次?为什么
  console.log(count, "render");
  return (
    <div>
      <h3>{count}</h3>

      <button
        onClick={async () => {
          await getData();
        }}
      >
        改变两个的值
      </button>
    </div>
  );
};

export default App;

源码地址,在线测试:

https://codesandbox.io/s/reac...

阅读 2.2k
2 个回答
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题