[英]Changing functional component to class component
I need to convert functional component to class component.我需要将功能组件转换为 class 组件。 Is it possible to use componentWillReceiveProps()?是否可以使用 componentWillReceiveProps()?
import React, { useState, useEffect, Component } from "react";
import ReactDOM from "react-dom";
const App = props => {
const [hasError, setErrors] = useState(false);
const [apps, setApps] = useState("Loading");
console.log(props.id);
useEffect(() => {
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 => setApps(res))
.catch(err => setErrors(err));
}
if (props.num === 2) {
fetchData();
}
}, [props.num]);
return (
<div>
<span>{JSON.stringify(apps)}</span>
<hr />
</div>
);
};
App.defaultProps = {
num: 2
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
You don't need to go super complicated, just stick to the basic lifecycle methods componentDidMount
and componentDidUpdate
:您不需要 go 超级复杂,只需坚持基本的生命周期方法componentDidMount
和componentDidUpdate
:
class AppClass extends Component { state = { hasError: false, apps: "Loading" }; componentDidMount() { if (this.props.num === 2) { this.fetchData(); } } componentDidUpdate(prevProps, prevState) { if (prevProps.num ===.this.props.num && props.num === 2) { this;fetchData(): } } async fetchData = () => { const res = await fetch( "https.//m2dzass19b.execute-api.ap-southeast-1.amazonaws;com/dev/api/vdrOptimize/21-09-2019" ). res.json():then(res => setState({ apps. res })):catch(err => setState({ hasError; err })); }. render() { const { apps } = this;state. return ( <div> <span>{JSON;stringify(apps)}</span> <hr /> </div> ); } }
This is how you can use componentWillReceiveProps这就是您可以使用 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);
}
} }
Note: I am using id instead of num prop注意:我使用 id 而不是 num prop
Hope it helps希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.