[英]Converting code from functional React hooks to class components
I'm currently trying to convert some hooks over to being inside class components in React.我目前正在尝试将一些钩子转换为 React 中的类组件。 I'm attempting to recreate the code that allows for session storage so that the app doesn't need to fetch from the API so much.
我正在尝试重新创建允许会话存储的代码,以便应用程序不需要从 API 中获取太多信息。 Here is the code:
这是代码:
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])
These are two useEffect hooks so it makes sense to me to go with a regular componentDidMount to get from the session storage.这是两个 useEffect 钩子,所以对我来说使用常规的 componentDidMount 从会话存储中获取是有意义的。 The only thing that I can't seem to figure out is how to recreate the second useEffect that sets session storage and fires only when searchTerm or state changes.
我似乎无法弄清楚的唯一一件事是如何重新创建第二个 useEffect 设置会话存储并仅在 searchTerm 或状态更改时触发。 searchTerm and state are simply two properties of the state.
searchTerm 和 state 只是状态的两个属性。 How could I implement this since componentDidMount only fires once when the app first mounts?
由于 componentDidMount 仅在应用程序首次安装时触发一次,我该如何实现? Thanks
谢谢
The only thing that I can't seem to figure out is how to recreate the second useEffect that sets session storage and fires only when searchTerm or state changes.
我似乎无法弄清楚的唯一一件事是如何重新创建第二个 useEffect 设置会话存储并仅在 searchTerm 或状态更改时触发。 searchTerm and state are simply two properties of the state.
searchTerm 和 state 只是状态的两个属性。
componentDidMount()
is only one of methods used by the class components you can recreate the second hook with componentWillUpdate() or shouldComponentUpdate(). componentDidMount()
只是类组件使用的方法之一,您可以使用 componentWillUpdate() 或 shouldComponentUpdate() 重新创建第二个钩子。
For example:例如:
componentWillUpdate(nextProps, nextState) {
if (this.props.searchTerm !== prevProps.searchTerm) {
...
}
}
You can check what lifecycle methods are available in class components by Googling "class component lifecycle" .您可以通过谷歌搜索“类组件生命周期”来检查类组件中可用的生命周期方法。
But as you can read in the comment to your questions Hooks can offer you more than class components, and recreating them is not trivial.但是,正如您在问题的评论中所读到的,Hook 可以为您提供的不仅仅是类组件,并且重新创建它们并非易事。 It is easier to move from the class component to the Hooks.
从类组件移动到 Hooks 更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.