我已经使用Redux创建了一个React组件,在将状态映射到道具之前,需要进行两次渲染。
使用此代码,
第一次呈现时“user.private”为null,第二次呈现时为false
正因为如此,在显示隐藏内容之前,加载页面会在显示“login”的一秒钟之间闪烁
我希望在默认情况下显示登录文本,但如果用户的private字段设置为false,我实际上不希望显示该文本。
class Content extends React.Component {
render() {
const { user } = this.props;
let show = false;
if (user.private === false) show = true
return (
<section>
{
show
? <p>hidden content</p>
: <p>login</p>
}
</section>
)
}
}
const mapStateToProps = state => ({
user: state.store.user
});
export default connect(mapStateToProps, {})(Content)发布于 2018-03-23 07:05:42
如果user最初未定义或为空,则可以在显示任何内容之前检查是否定义了user和/或其属性private:
if (this.props.user == null || this.props.user.private) {
show = false;
}如果this.props.user的值未定义或为空,则double equals null将使条件为true。您也可以使用!this.props.user。
如果您在获取user的初始值之前就将其设置为{},那么您必须这样做:
if (this.props.user.private == null || this.props.user.private) {
show = false;
}发布于 2018-03-23 07:11:24
您可以使用switch来处理null情况(您可以显示一个加载器,也可以通过返回null来呈现任何内容)我使用组件状态来说明这一想法,但是您可以将其应用于redux连接的组件。
class App extends React.Component {
state = {
user : {
private : null
}
}
componentDidMount () {
setTimeout(() => {
this.setState(() => {
return {
user : {
private : true
}
}
});
}, 2000);
}
renderContent () {
const { user } = this.state;
switch (user.private) {
case null : return <span>Loading...</span>
case false : return <p>login</p>
default : return <p>hidden content</p>
}
}
render () {
return (
<div>
{this.renderContent()}
</div>
);
}
}
ReactDOM.render(
<App/>,
document.querySelector('#root')
);https://stackoverflow.com/questions/49439635
复制相似问题