我需要将功能组件转换为类组件。可以使用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);
答案 0 :(得分:1)
您并不需要太复杂,只需坚持使用基本生命周期方法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>
);
}
}
答案 1 :(得分:-2)
这是您可以使用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
希望有帮助