我如何选择在JSX中包含一个元素?下面是一个使用横幅的示例,如果已经传入,该横幅应该在组件中.我想要避免的是必须在if语句中复制HTML标记.
render: function () {
var banner;
if (this.state.banner) {
banner = <div id="banner">{this.state.banner}</div>;
} else {
banner = ?????
}
return (
<div id="page">
{banner}
<div id="other-content">
blah blah blah...
</div>
</div>
);
}
Run Code Online (Sandbox Code Playgroud) 我花了很多时间阅读 React Hooks,虽然它的功能看起来比使用具有本地状态和生命周期方法的类更直观、可读和简洁,但我一直在阅读有关 Hooks 替代 HOCs 的参考资料。
我在 React 应用程序中使用的主要 HOC 是 withAuth —— 基本上是一个检查 currentUser(存储在 Redux 状态)是否经过身份验证的函数,如果是,则呈现包装的组件。
这是一个实现:
import React, { Component } from "react";
import { connect } from "react-redux";
export default function withAuth(ComponentToBeRendered) {
class Authenticate extends Component {
componentWillMount() {
if (this.props.isAuthenticated === false) {
this.props.history.push("/signin");
}
}
componentWillUpdate(nextProps) {
if (nextProps.isAuthenticated === false) {
this.props.history.push("/signin");
}
}
render() {
return <ComponentToBeRendered {...this.props} />;
}
}
function mapStateToProps(state) {
return { isAuthenticated: state.currentUser.isAuthenticated };
}
return …Run Code Online (Sandbox Code Playgroud)