向函数组件添加状态和生命周期方法 [英] Add state and lifecycle methods to Function Components
问题描述
如何在功能组件中重写此代码?
How can I rewrite this code in a functional component?
我想向功能组件添加状态和生命周期方法.
I want to add state and lifecycle methods to the Functional Component.
这是来自类组件的 componentDidMount
和 componentWillReceiveProps
的代码.
This is the code is for componentDidMount
and componentWillReceiveProps
from the class component.
class TherapistProfiles extends React.Component {
state = {
page: 1,
therapists: [],
hasMore: true,
resultsTitle: 'Top Therapist Profiles',
pageLoading: false
}
topProfilesUrl = 'therapists/top/profiles'
searchByNameUrl = 'therapists/search/name'
componentDidMount = () => {
this.getTopTherapists()
window.scrollTo(0, 0);
}
componentWillReceiveProps = (newProps) => {
let apiData = newProps.apiData;
if (apiData.topProfiles && apiData.topProfiles.success) {
let therapists = apiData.topProfiles.therapists
let hasMore = true
if (therapists.length < 10) {
hasMore = false
}
this.setState(() => ({
therapists: this.state.therapists.concat(therapists),
hasMore: hasMore,
pageLoading: false
}))
} else if (apiData.therapistsByName && apiData.therapistsByName.success) {
let therapists = apiData.therapistsByName.therapists,
resTitle = therapists.length ?
`Results for "${this.state.searchName}"`
: `Looks like there are no results for "${this.state.searchName}"`
this.setState(() => ({
therapists: therapists,
hasMore: false,
pageLoading: false,
resultsTitle: resTitle
}))
}
}
推荐答案
您将可以使用 useState 钩子作为组件状态,并使用 useEffect 钩子代替 ComponentDidUpdate 和 ComponentWillReceiveProps.
You will can make use of the useState hook for the component state, and useEffect hook to replace ComponentDidUpdate and ComponentWillReceiveProps.
首先,您使用 useState
钩子来维护组件状态.
First, you use the useState
hook to maintain the component state.
const [ therapistProfilesState, setTherapistProfilesState ] = useState({
page: 1,
therapists: [],
hasMore: true,
resultsTitle: 'Top Therapist Profiles',
pageLoading: false
});
接下来,要替换 ComponentDidMount
,您将依赖项数组设置为空数组,这样 useEffect
钩子将在 init 上运行一次:
Next, to replace ComponentDidMount
, you set the dependency array as an empty array such that the useEffect
hook will run once on init:
useEffect(() => {
getTopTherapists()
window.scrollTo(0, 0);
}, []);
至于 ComponentWillReceiveProps
,你将有另一个 useEffect
钩子和 props
作为依赖数组的一部分,这样它就会在什么时候运行props
已更新.我不会写完整的代码,因为它太长了,但这是一个起点:
And as for ComponentWillReceiveProps
, you will have another useEffect
hook with props
as part of the dependency array, such that it will run when props
are updated. I won't write the full code as it is too long, but here is a starting point:
useEffect(() => {
if (something) {
setTherapistProfilesState(...);
}
}, [props]);
这篇关于向函数组件添加状态和生命周期方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!