gpt4 book ai didi

javascript - 本项目如何将 React 类组件转换为函数组件

转载 作者:行者123 更新时间:2023-12-01 23:19:51 25 4
gpt4 key购买 nike

import React, { Component } from 'react';
import { Route } from 'react-router-dom';

import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';

import * as baseActions from '../../redux/modules/base';
import { AuthWrapper } from '../../components/Auth';
import { Login, Register } from '../../containers/Auth';

class Auth extends Component {
// 페이지에 진입 할 때 헤더를 비활성화
componentWillMount() {
this.props.BaseActions.setHeaderVisibility(false);
}

// 페이지에서 벗어 날 때 다시 활성화
componentWillUnmount() {
this.props.BaseActions.setHeaderVisibility(true);
}

render() {
return (
<AuthWrapper>
<Route path="/auth/login" component={Login} />
<Route path="/auth/register" component={Register} />
</AuthWrapper>
);
}
}

export default connect(
(state) => ({

}),
(dispatch) => ({
BaseActions: bindActionCreators(baseActions, dispatch)
})
)(Auth);

我想把这个文件转换成函数组件我试过这样的

const Auth = (BaseActions) => {
useEffect(() => {
BaseActions.setHeaderVisibility(false);
return BaseActions.setHeaderVisibility(true);
})

但是发生了错误 enter image description here

我不知道this.props所以我想知道如何转换这个类组件

最佳答案

BaseActions.setHeaderVisibility 不是你的函数,因为你还没有解构你的 Prop 数据。现在 BaseAction 被视为此组件的 Prop 。

以下片段中提到了消除此问题的方法:

const Auth=(props)=>{
const { BaseActions, ...rest} = props;
useEffect(() => {
BaseActions.setHeaderVisibility(false);
return () => BaseActions.setHeaderVisibility(true);
}, []);

const Auth=({ BaseActions, ...rest})=>{
useEffect(() => {
BaseActions.setHeaderVisibility(false);
return () => BaseActions.setHeaderVisibility(true);
}, []);

这里的点点代表在连接包装器中定义的 Prop 的名称。

const Auth=({ BaseActions, ... , .... , ... , otherProps})=>{
useEffect(() => {
BaseActions.setHeaderVisibility(false);
return () => BaseActions.setHeaderVisibility(true);
}, []);

关于javascript - 本项目如何将 React 类组件转换为函数组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68234863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com