Javascript 将功能组件更改为类组件
我需要将功能组件转换为类组件。是否可以使用componentWillReceiveProps()Javascript 将功能组件更改为类组件,javascript,reactjs,Javascript,Reactjs,我需要将功能组件转换为类组件。是否可以使用componentWillReceiveProps() import React,{useState,useffect,Component}来自“React”; 从“react dom”导入react dom; const App=props=>{ 常量[hasError,setErrors]=useState(false); const[apps,setApps]=useState(“加载”); console.log(props.id); useff
import React,{useState,useffect,Component}来自“React”;
从“react dom”导入react dom;
const App=props=>{
常量[hasError,setErrors]=useState(false);
const[apps,setApps]=useState(“加载”);
console.log(props.id);
useffect(()=>{
异步函数fetchData(){
const res=等待取数(
"https://m2dzass19b.execute-api.ap-southeast-1.amazonaws.com/dev/api/vdrOptimize/21-09-2019"
);
物件
.json()
。然后(res=>setApps(res))
.catch(err=>setErrors(err));
}
如果(props.num==2){
fetchData();
}
},[props.num]);
返回(
{JSON.stringify(应用程序)}
);
};
App.defaultProps={
总数:2
};
const rootElement=document.getElementById(“根”);
render(,rootElement);
这就是如何使用componentWillReceiveProps
UNSAFE_componentWillReceiveProps(nextProps) {
async function fetchData() {
const res = await fetch(
"https://m2dzass19b.execute-api.ap-southeast-1.amazonaws.com/dev/api/vdrOptimize/21-09-2019"
);
res
.json()
.then(res => this.setState({ apps: res }))
.catch(err => this.setState({ hasError: err }));
}
if (nextProps.id === 2) {
fetchData.call(this);
}
}
注意:我使用的是id而不是num prop
希望它能有所帮助您不需要过于复杂,只要坚持使用基本的生命周期方法
componentDidMount
和componentdiddupdate
:
class AppClass扩展组件{
状态={
错误:错,
应用程序:“正在加载”
};
componentDidMount(){
if(this.props.num==2){
这是fetchData();
}
}
componentDidUpdate(prevProps、prevState){
if(prevProps.num==!this.props.num&&props.num==2){
这是fetchData();
}
}
异步获取数据=()=>{
const res=等待取数(
"https://m2dzass19b.execute-api.ap-southeast-1.amazonaws.com/dev/api/vdrOptimize/21-09-2019"
);
物件
.json()
.then(res=>setState({apps:res}))
.catch(err=>setState({hasError:err}));
};
render(){
const{apps}=this.state;
返回(
{JSON.stringify(应用程序)}
);
}
}
请勿使用。而且React正在推动功能越来越强大,那么为什么要将已经具有功能的组件转换为类呢?因为我使用的环境使用类它们彼此兼容,您不必将类与类一起使用。你可以两者都用,你可以用。此外,useEffect会设置异步值解析时的状态,但不会检查组件是否仍在装载。您可以在props.id更改时使用componentdiddupdate
获取数据,并使用componentDidMount
进行初始获取(并在尚未获取数据时显示良好的加载状态)。将抓取逻辑移动到函数中,您可以从两种生命周期方法调用它。您不应该使用文档,因为文档中有很多替代方法,所以为什么要继续使用它?我知道它已被弃用,这就是我使用不安全组件WillReceiveProps的原因,
UNSAFE_componentWillReceiveProps(nextProps) {
async function fetchData() {
const res = await fetch(
"https://m2dzass19b.execute-api.ap-southeast-1.amazonaws.com/dev/api/vdrOptimize/21-09-2019"
);
res
.json()
.then(res => this.setState({ apps: res }))
.catch(err => this.setState({ hasError: err }));
}
if (nextProps.id === 2) {
fetchData.call(this);
}