钩子中功能组件的生命周期转换

时间:2020-02-14 07:13:27

标签: reactjs react-hooks

我的代码中有这个componentWillReceiveProps生命周期,我想为一个功能组件编写它。如我所见,这只能通过React Hooks来实现。问题是我不太了解,需要帮助。

那么,如何将其编写在功能组件中?

我看到了一些例子,但并不完全是这种情况。

componentWillReceiveProps = (newProps) => {
    const apiData = newProps.apiData;

    if (apiData.articles) {
        this.setState(() => ({
            pageLoading: false,
            articles: apiData.articles.articles,
        }), () => {
            //this.filterDisplayedArticles()
        })
    } else if (apiData.articleSearch && apiData.articleSearch.success) {
        let articles = apiData.articleSearch.articles;
        this.setState(() => ({
            pageLoading: false,
            articles: articles
        }))
    }
}

2 个答案:

答案 0 :(得分:0)

您可以在此处使用useEffect挂钩,根据所需参数应用更改
并使用useState钩子来跟踪您的状态

import React, { useEffect, useState } from "react";

function DoSomething({ apiData }) {
  const { articles, articleSearch } = apiData;
  const { state, setState } = useState({ pageLoading: true, articles: [] });

  useEffect(() => {
    if (articles) {
      setState({
        pageLoading: false,
        articles: apiData.articles.articles
      });
    } else if (articleSearch && articleSearch.success) {
      setState({
        pageLoading: false,
        articles: articleSearch.articles
      });
    }
  }, [articles, articleSearch]);

  return <div>I'm {state.pageLoading ? "loading" : "done loading"}</div>;
}

Play with it live :)

答案 1 :(得分:0)

您可以使用useState挂钩进行状态管理,组件将收到props,didmount和willmount进行使用效果挂钩可让您查看以下功能组件代码

import React,{useState,useEffect} from 'react'

const App =() =>{
  const [pageLoading,setLoading] = useState(false)
const [articles,setarticles] = useState([])
useEffect((newProps) => {
  const apiData = newProps.apiData;

if (apiData.articles) {
  setLoading(false)
  setarticles(apiData.articles.articles)

} else if (apiData.articleSearch && apiData.articleSearch.success) {
 let articles = apiData.articleSearch.articles;
  setLoading(false)
 setarticles(articles)
}
 }, [pageLoading,articles])  
 return (
   ....child
 )
}
  export default App