【发布时间】:2021-08-31 17:53:05
【问题描述】:
我遇到了一个组件从 React JS 中的前一个组件继承信息的问题。在下面的示例中,我试图从 props 中的登录用户那里获取信息。但是,在组装仪表板页面时,我无法加载此信息 (ComponentDidMount)。
componente/BaseDashboard.js
import React from 'react'; import Header from
'../../components/Header';
import { connect } from 'react-redux'; import * as actions from
'../../store/actions'; import Footer from '../../components/Footer';
class BaseDashboard extends React.Component {
state = {
statusMenu: true
}
alertMenu() {
this.setState({ statusMenu: !this.state.statusMenu })
}
alertMenu = this.alertMenu.bind(this);
render() {
return (
<>
<div className="wrapper">
<Header handleLogout={this.props.handleLogout} userData={this.props} alertMenu={this.alertMenu} />
<div className="content-wrapper">
{this.props.children}
</div>
<Footer handleLogout={this.props.handleLogout} userData={this.props} alertMenu={this.alertMenu} />
</div>
</>
);
} }
export default connect(null, actions)(BaseDashboard);
组件/index.js
import React from 'react'; import BaseDashboard from
'./BaseDashboard'; import { connect } from 'react-redux'; import * as
actions from '../../store/actions';
const baseDashboard = Component => {
class ComponentBaseDashboard extends React.Component {
componentDidMount() {
const { authorized, getViewUser, history } = this.props;
getViewUser();
if (!authorized) {
return history.replace("/");
}
}
componentDidUpdate(nextProps) {
const { authorized, history } = this.props;
if (!nextProps.authorized || !authorized) {
return history.replace("/");
}
}
render() {
return (
<BaseDashboard>
<Component {...this.props} />
</BaseDashboard>
);
}
}
const mapStateToProps = state => ({
authorized: state.auth.authorized,
user: state.auth.user
});
return connect(mapStateToProps, actions)(ComponentBaseDashboard); }
export default baseDashboard;
在此方法中,当我为 this.props.user 运行 console.log 时,出现消息“TypeError:无法读取未定义的属性” 页面/Dashboard.js
componentDidMount() {
const { user } = this.props;
console.log(this.props);
this.setState({ user: user })
}
我在路线中以这种方式调用的仪表板页面
【问题讨论】:
-
顺便说一句,基于类的组件和带有生命周期方法(而不是钩子)的 Redux 现在看起来有点过时了。
-
你需要返回你声明的类。否则它只是一个不做任何事情的本地声明。
标签: javascript reactjs redux react-redux