首页 > 解决方案 > 反应类继承

问题描述

我遇到了一个组件从 React JS 中的前一个组件继承信息的问题。在下面的示例中,我试图从 props 中的登录用户那里获取信息。但是,组装仪表板页面(ComponentDidMount)时,我无法加载此信息。

组件/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 pages/Dashboard.js 运行 console.log 时,出现消息“TypeError:无法读取未定义的属性”

componentDidMount() {
   const { user } = this.props;
   console.log(this.props);
   this.setState({ user: user })
}

我在路线中以这种方式调用的仪表板页面

标签: javascriptreactjsreduxreact-redux

解决方案


您说this.props在未知组件中未定义(您发布了 2 但没有记录 this.props)。

这是一个最小示例示例,没有显示您的代码应该工作的所有无关代码:

const { Provider, connect } = ReactRedux;
const { createStore, applyMiddleware, compose } = Redux;

const initialState = { value: 22 };
const reducer = (state, { type, payload }) => {
  return state;
};

class BaseDashboard extends React.Component {
  componentDidMount() {
    console.log(
      'base props no problem:',
      Boolean(this.props)
    );
  }
  render() {
    return <div>hello world</div>;
  }
}
const ConnectedBaseDashboard = connect()(BaseDashboard);
const baseDashboard = (Component) => {
  class ComponentBaseDashboard extends React.Component {
    componentDidMount() {
      console.log('props no problem:', this.props);
    }
    render() {
      return (
        <BaseDashboard>
          <Component {...this.props} />
        </BaseDashboard>
      );
    }
  }
  const mapStateToProps = (state) => state;
  return connect(
    mapStateToProps,
    {}
  )(ComponentBaseDashboard);
};

//creating store with redux dev tools
const composeEnhancers =
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
  reducer,
  initialState,
  composeEnhancers(
    applyMiddleware(
      () => (next) => (action) => next(action)
    )
  )
);
const App = baseDashboard(ConnectedBaseDashboard);

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.2.0/react-redux.min.js"></script>

<div id="root"></div>

也许您可以使用上面的代码段来演示您在问题中遇到的问题。


推荐阅读