【发布时间】:2020-02-13 15:43:14
【问题描述】:
如何在功能组件中重写此代码?
我想为功能组件添加状态和生命周期方法。
这是类组件中componentDidMount 和componentWillReceiveProps 的代码。
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
}))
}
}
【问题讨论】:
标签: javascript reactjs react-hooks