将状态和生命周期方法添加到功能组件

时间:2020-02-13 15:43:14

标签: javascript reactjs react-hooks

如何在功能组件中重写此代码?

我想向功能组件添加状态和生命周期方法。

这是来自类组件的componentDidMountcomponentWillReceiveProps的代码。

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
            }))
        }
    }

2 个答案:

答案 0 :(得分:1)

您将可以使用useState挂钩来获取组件状态,并使用useEffect挂钩来替换ComponentDidUpdate和ComponentWillReceiveProps。

首先,您使用useState挂钩来维护组件状态。

const [ therapistProfilesState, setTherapistProfilesState ] = useState({
  page: 1,
  therapists: [],
  hasMore: true,
  resultsTitle: 'Top Therapist Profiles',
  pageLoading: false
});

接下来,要替换ComponentDidMount,请将依赖项数组设置为空数组,以使useEffect挂钩在初始化时运行一次:

useEffect(() => {
  getTopTherapists()
  window.scrollTo(0, 0);
}, []);

对于ComponentWillReceiveProps,您将有另一个useEffect钩子与props作为依赖项数组的一部分,这样它将在更新props时运行。我不会写完整的代码,因为它太长了,但这是一个起点:

useEffect(() => {
  if (something) {
    setTherapistProfilesState(...);
  }
}, [props]);

答案 1 :(得分:0)

正在寻找componentDidMountcomponentWillReceiveProps的函数组件中没有像基于类的组件那样的东西。相反,您可以使用useEffect挂钩。阅读文档:

如果您熟悉React类的生命周期方法,则可以将useEffect挂钩视为componentDidMountcomponentDidUpdatecomponentWillUnmount的组合。

让我给你举个简单的例子:

const Home = () => {
   // defining states
   const [page, setPage] = useState(1);

   // implementing side effects below
   // similarly like lifecycle events in class component
   useEffect(() => {
      console.log('your component is ready to fetch data');

      // maybe you want to fetch data from an API here
   }, []);

   return <h1>Hello function component</h1>;
}

建议阅读:Using the Effect Hook

希望对您有帮助!