首页 > 解决方案 > ReactJs:由于不推荐使用componentWillMount,如何在组件安装之前执行代码?

问题描述

我试图在组件安装之前有条件地将用户重定向到主页:

 componentWillMount(){
    console.log("componentWillMount is called.")
    let userHasNotChosenOpportunity = true
    if (userHasNotChosenOpportunity) {
      this.props.history.push("/home")
    }
  }

我有两个问题:

  1. componentWillMount永远不会被调用
  2. componentWillMount已弃用,并且似乎没有其他方法可以在组件安装之前执行代码。

有什么建议么?

标签: javascriptreactjsreduxreact-lifecycle

解决方案


我是这样解决的:

import React from "react";
import { Route, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import PropTypes from "prop-types";
const OpportunityRedirectRoute = ({
  component: Component,
  opportunities,
  ...rest
}) => {
  let userHasNotChosenOpportunity =
    Object.keys(opportunities.chosen_opportunity).length === 0 &&
    opportunities.chosen_opportunity.constructor === Object;

  return (
    <Route
      {...rest}
      render={(props) =>
        userHasNotChosenOpportunity ? (
          <Redirect to="/courses" />
        ) : (
          <Component {...props} />
        )
      }
    />
  );
};

OpportunityRedirectRoute.propTypes = {
  opportunities: PropTypes.object.isRequired,
};

const mapStateToProps = (state) => ({
  opportunities: state.opportunities,
});

export default connect(mapStateToProps)(OpportunityRedirectRoute);

在 App.js 中:

 <OpportunityRedirectRoute
              exact
              path="/opportunity"
              component={OpportunityPage}
            />

推荐阅读