React中如何将类组件转换为支持Hooks的函数组件?
类组件转函数组件实现方案
核心对应关系
- 类
render方法:直接对应函数组件的返回值,函数组件的主体渲染逻辑和原render完全一致 - 类
constructor一次性初始化逻辑:使用空依赖数组的useEffect实现,仅在组件首次挂载时执行1次,匹配你当前的初始化需求 - 类实例自定义属性(如
this.previousLocation):使用useRef存储,修改ref.current不会触发组件重渲染,行为和类实例属性完全一致 withStyles高阶组件无需调整,可直接包裹函数组件导出
转换后完整代码
import { useEffect, useRef } from 'react'; const MainSwitchNavigator = (props) => { const { location, history, classes } = props; // 对应原类组件的 this.previousLocation 实例变量 const previousLocation = useRef(location); // 对应原constructor内的初始化逻辑,仅执行一次 useEffect(() => { navigator.setTopHistory(history); }, []); // 对应原render方法返回内容 return ( <main> <div className={classes.container}> <Switch> <Route path="/" exact component={OnboardingScreen} /> <Route path="/consent" component={ConsentScreen} /> <Route path="/privacy-policy" component={PrivacyPolicyScreen} /> <Route path="/term-service" component={TermOfServiceScreen} /> <Route path="/sign-in" component={SignInScreen} /> <Route path="/sign-up" component={SignUpScreen} /> <Route path="/send-code" component={SendCodeScreen} /> <Route path="/verify-code" component={VerifyCodeScreen} /> <Route path="/new-password" component={NewPasswordScreen} /> <Route path="/home" component={MasterContainer} /> <Route path="/covid-testing-consent" component={CovidTestingConsentScreen} /> <Route component={NoMatch} /> </Switch> <ToastContainer /> </div> </main> ); }; const NoMatch = ({ location }) => ( <div> <h3>Page not found</h3> </div> ); export default withStyles(styles)(MainSwitchNavigator);
注意事项
如果后续需要更新previousLocation的值,直接修改previousLocation.current即可,和原类组件修改this.previousLocation的效果完全一致。
内容的提问来源于stack exchange,提问作者Jake Castillo
相关产品推荐
相关产品推荐

