我一直在学习有关 React.js 函数组件的更多信息,并开始将我的一个 React.js 应用程序转换为使用它们而不是标准的 React 组件。在我的 React 组件中,我一直在 componentDidMount()
函数中进行 AJAX/API 调用。由于函数组件中不存在该函数,我不确定将它们放在哪里。
我在 React.js 网站上找不到答案,only page I could find on AJAX and APIs显示在 componentDidMount()
函数中使用 React 标准组件进行这些调用。
最佳答案
这就是 React hooks 为我们提供的 - 在功能组件中实现副作用的方法:
https://reactjs.org/docs/hooks-effect.html
来自文档页面:
If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.
例如:
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>
);
}
关于javascript - 我应该在 React.js 函数组件中哪里进行 AJAX 和 API 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58633438/