rag*_*ag9 0 javascript ajax reactjs
我一直在了解有关 React.js 函数组件的更多信息,并开始将我的一个 React.js 应用程序转换为使用它们而不是标准的 React 组件。在我的 React 组件中,我一直在函数中进行 AJAX/API 调用componentDidMount()。由于该函数不存在于函数组件中,我不确定将它们放在哪里。
我在 React.js 网站上找不到答案,我在 AJAX 和 API 上找到的唯一页面显示了如何使用函数中的 React 标准组件进行这些调用componentDidMount()。
这就是 React hooks 为我们提供的——在功能组件中产生副作用的方法:
\nhttps://reactjs.org/docs/hooks-effect.html
\n从文档页面:
\n\n\n如果你\xe2\x80\x99熟悉React类生命周期方法,你可以将useEffect Hook想象为componentDidMount、componentDidUpdate和componentWillUnmount的组合。
\n
例如:
\nimport React, { useState, useEffect } from \'react\';\n\nfunction Example() {\n const [count, setCount] = useState(0);\n\n // Similar to componentDidMount:\n useEffect(() => {\n //do an ajax call here\n }, []);\n\n return (\n <div>\n <p>You clicked {count} times</p>\n <button onClick={() => setCount(count + 1)}>\n Click me\n </button>\n </div>\n );\n}\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
1283 次 |
| 最近记录: |