javascript - ReactJs:由于不推荐使用componentWillMount,如何在组件安装之前执行代码?
问题描述
我试图在组件安装之前有条件地将用户重定向到主页:
componentWillMount(){
console.log("componentWillMount is called.")
let userHasNotChosenOpportunity = true
if (userHasNotChosenOpportunity) {
this.props.history.push("/home")
}
}
我有两个问题:
componentWillMount
永远不会被调用componentWillMount
已弃用,并且似乎没有其他方法可以在组件安装之前执行代码。
有什么建议么?
解决方案
我是这样解决的:
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}
/>
推荐阅读
- flutter - 如何在颤动中创建具有圆形边缘的自定义容器?
- python - 如何在 Pyglet 中的图像纹理上添加文本
- python - 对列值进行排序并将索引列附加到其中
- mongodb - Mongodb 连接限制是每个分片还是每个集群?
- python - For-in-loop 多维列表 IndexError
- c# - 有没有办法将 2 个数据网格的行高链接到始终相同?
- c# - C# - 如何扩展 UserLoginEventSuccessEvent
- reactjs - 如何使用 react-router-dom 在“x”秒后“重定向到”
- python - 如何在seaborn中增加子图的大小
- javascript - 绕过浏览器 URL 编码以从查询参数中反射 XSS