【问题标题】:Add state and lifecycle methods to Function Components向函数组件添加状态和生命周期方法
【发布时间】:2020-02-13 15:43:14
【问题描述】:

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

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

这是类组件中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
            }))
        }
    }

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案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]);
    

    【讨论】:

      【解决方案2】:

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

      如果你熟悉 React 类的生命周期方法,你可以把 useEffectHook 想成 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

      希望对你有帮助!

      【讨论】:

      • 我认为问题在于 OP 希望我们为他们完成所有工作,并将他们基于类的组件转换为函数组件。
      • @zero298 我想通过我提供的示例,我正在帮助 OP 很好地开始使用 useEffect 挂钩,当然它需要像往常一样进一步实施和阅读。但它给出了这个想法。
      猜你喜欢
      • 1970-01-01
      • 2016-01-13
      • 1970-01-01
      • 2017-11-29
      • 2018-05-05
      • 2020-06-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      相关资源
      最近更新 更多