我应该在哪里在 React.js 函数组件中进行 AJAX 和 API 调用? [英] Where should I make AJAX and API calls in React.js function components?

查看:31
本文介绍了我应该在哪里在 React.js 函数组件中进行 AJAX 和 API 调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习有关 React.js 函数组件的更多信息,并已开始转换我的一个 React.js 应用程序以使用它们而不是标准的 React 组件.在我的 React 组件中,我一直在 componentDidMount() 函数中进行 AJAX/API 调用.由于该函数不存在于函数组件中,我不确定将它们放在哪里.

我无法在 React.js 站点上找到答案,只有我能找到的页面find on AJAX 和 API 显示使用 componentDidMount() 函数中的标准组件进行这些调用.

解决方案

这就是 React hooks 给我们的 - 在函数式组件中处理副作用的方法:

https://reactjs.org/docs/hooks-effect.html

来自文档页面:

<块引用>

如果您熟悉 React 类的生命周期方法,您可以将 useEffect Hook 视为 componentDidMount、componentDidUpdate 和 componentWillUnmount 的组合.

例如:

import React, { useState, useEffect } from 'react';函数示例(){const [count, setCount] = useState(0);//类似于 componentDidMount 和 componentDidUpdate:useEffect(() => {//在这里做一个ajax调用});返回 (<div><p>您点击了 {count} 次</p><button onClick={() =>setCount(count + 1)}>点击我

);}

I've been learning more about React.js function components and have started transitioning one of my React.js applications to use them instead of the standard react components. In my react components I had been making AJAX/API call(s) in the componentDidMount() function. Since that function doesn't exist in function components I am unsure where to put them.

I couldn't find the answer on the React.js site, the only page I could find on AJAX and APIs shows making those calls with react standard components in the componentDidMount() function.

解决方案

This is what React hooks gives us - ways to do side effects in functional components:

https://reactjs.org/docs/hooks-effect.html

from the doc page:

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

for example:

import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    //do an ajax call here
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

这篇关于我应该在哪里在 React.js 函数组件中进行 AJAX 和 API 调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆