Javascript 在React.js函数组件中,我应该在哪里进行AJAX和API调用?
我已经学习了更多关于React.js函数组件的知识,并开始转换我的一个React.js应用程序来使用它们,而不是标准的React组件。在react组件中,我一直在Javascript 在React.js函数组件中,我应该在哪里进行AJAX和API调用?,javascript,ajax,reactjs,Javascript,Ajax,Reactjs,我已经学习了更多关于React.js函数组件的知识,并开始转换我的一个React.js应用程序来使用它们,而不是标准的React组件。在react组件中,我一直在componentDidMount()函数中调用AJAX/API。由于该函数不存在于函数组件中,我不确定将它们放在何处 我在React.js网站上找不到答案,在componentDidMount()函数中显示使用React标准组件进行这些调用。这就是React钩子为我们提供的-在功能组件中执行副作用的方法: 从文档页面: 如果您熟悉R
componentDidMount()
函数中调用AJAX/API。由于该函数不存在于函数组件中,我不确定将它们放在何处
我在React.js网站上找不到答案,在
componentDidMount()
函数中显示使用React标准组件进行这些调用。这就是React钩子为我们提供的-在功能组件中执行副作用的方法:
从文档页面:
如果您熟悉React类生命周期方法,可以将useEffect钩子看作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>
);
}
import React,{useState,useffect}来自“React”;
函数示例(){
const[count,setCount]=useState(0);
//与componentDidMount和componentDidUpdate类似:
useffect(()=>{
//在这里进行ajax调用
});
返回(
您单击了{count}次
设置计数(计数+1)}>
点击我
);
}
您可以使用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);
import React,{Component}来自'React';
从“反应纯生命周期”导入生命周期;
常量方法={
组件安装(道具){
//在这里打电话
}
};
const Channels=props=>(
你好
)
导出默认生命周期(方法)(通道);
搜索useffect()函数