[英]Converting React Class to Functional Components with Hooks. How to fix “uncontrolled input” error
[英]Converting code from functional React hooks to class components
我目前正在嘗試將一些鈎子轉換為 React 中的類組件。 我正在嘗試重新創建允許會話存儲的代碼,以便應用程序不需要從 API 中獲取太多信息。 這是代碼:
useEffect(() => {
if(sessionStorage.homeState){
// console.log("Getting from session storage");
setState(JSON.parse(sessionStorage.homeState));
setLoading(false);
}else{
// console.log("Getting from API");
fetchMovies(POPULAR_BASE_URL);
}
}, [])
useEffect(() => {
if(!searchTerm){
// console.log("Writing to session storage");
sessionStorage.setItem('homeState', JSON.stringify(state));
}
}, [searchTerm, state])
這是兩個 useEffect 鈎子,所以對我來說使用常規的 componentDidMount 從會話存儲中獲取是有意義的。 我似乎無法弄清楚的唯一一件事是如何重新創建第二個 useEffect 設置會話存儲並僅在 searchTerm 或狀態更改時觸發。 searchTerm 和 state 只是狀態的兩個屬性。 由於 componentDidMount 僅在應用程序首次安裝時觸發一次,我該如何實現? 謝謝
我似乎無法弄清楚的唯一一件事是如何重新創建第二個 useEffect 設置會話存儲並僅在 searchTerm 或狀態更改時觸發。 searchTerm 和 state 只是狀態的兩個屬性。
componentDidMount()
只是類組件使用的方法之一,您可以使用 componentWillUpdate() 或 shouldComponentUpdate() 重新創建第二個鈎子。
例如:
componentWillUpdate(nextProps, nextState) {
if (this.props.searchTerm !== prevProps.searchTerm) {
...
}
}
您可以通過谷歌搜索“類組件生命周期”來檢查類組件中可用的生命周期方法。
但是,正如您在問題的評論中所讀到的,Hook 可以為您提供的不僅僅是類組件,並且重新創建它們並非易事。 從類組件移動到 Hooks 更容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.