我应该在哪里在 React.js 函数组件中进行 AJAX 和 API 调用?

IT技术 javascript ajax reactjs
2021-05-08 23:11:46

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

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

2个回答

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

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

从文档页面:

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

例如:

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-pure-lifecycle 为功能组件添加生命周期函数。

例子:

import React, { Component } from 'react';
import lifecycle from 'react-pure-lifecycle';

const methods = {
    componentDidMount(props) {
    //ajax call here
    }
};

const Channels = props => (
      <h1>Hello</h1>
  )

export default lifecycle(methods)(Channels);