我的代码中有这个组件WillReceiveProps生命周期,我想为功能组件编写它。正如我所看到的,这只有使用 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
}))
}
}
您可以使用useState钩子进行状态管理和组件将接收props,didmount和willmount用于use效果钩子让我们看看下面的功能组件代码
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
您可以使用此处的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>;
}
:)现场玩它