【问题标题】:How to get data from an API only once when the page is loaded using axios.get method?使用 axios.get 方法加载页面时,如何仅从 API 获取数据一次?
【发布时间】:2023-03-11 22:08:01
【问题描述】:

我是 React 的初学者,我只想在加载特定页面时从我的 API 中获取一次数据,并将其保存到一个变量中,即“todo”。我可以在我的后端代码中看到此代码正在向 api 发送连续请求。

const [todo, setTodo] = useState({})
        const fetchdata = async () => {
            const res = await axios.get(`http://localhost:8000/api/get-todo/${nid}`);
            setTodo(res.data);
        };
        useEffect(() => {
            fetchdata();
        },)

【问题讨论】:

    标签: reactjs react-hooks axios react-router fastapi


    【解决方案1】:

    您需要在 useEffect 钩子的末尾使用方括号 ([]) 来发出发送请求一次

    useEffect(() => {
        fetchdata();
    }, [])
    

    【讨论】:

      猜你喜欢
      • 2020-12-08
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      • 2019-10-10
      • 2021-08-23
      • 2016-10-30
      • 2011-08-09
      • 2012-07-06
      相关资源
      最近更新 更多