繁体   English   中英

redux状态值返回未定义

[英]redux state value returns undefined

我通过redux connect声明状态

const mapStateToProps = state => ({
    singleBase: state.interaction.base
});

export default requiresLogin()(connect(mapStateToProps)(BasePage));

通过控制台日志console.log(this.props.singleBase);很好地显示状态console.log(this.props.singleBase);

id: "5b757e6743904228586a5a7f"
creatorId: "5b6e39ce08406602d0a9e125"
title: "tester"
currentUsers: 2
messages: 0

在后端,我有以下模型:

const BaseSchema = mongoose.Schema({
  creatorId: { type: mongoose.Schema.Types.ObjectId, required: true },
  title: { type: String, required: true },
  currentUsers: { type: Number, default: 0 },
  messages: { type: Number, default: 0 }
});

但是,当我尝试控制台记录currentUsers的值时: console.log(this.props.singleBase.currentUsers); 我收到以下错误: Cannot read property 'currentUsers' of undefined

我尝试将Schema设置为纯数字(例如5)以及文本“ 5”。 两者均无效。 我缺少什么细节才能获得currentUsers的价值?

编辑和解决方案:

const users =
    this.props.singleBase && this.props.singleBase.currentUsers !== undefined
    ? this.props.singleBase.currentUsers
    : 0;
return (
    <div>
      <h2>{users}</h2>
    </div>
);

在这里,我们确保this.props.singleBase存在且为true,同时我确保this.props.singleBase.currentUsers具有未定义的值。 如果两个都为真,则显示this.props.singleBase.currentUsers。 关键是在异步操作完成之前,singleBase将为空。 填充数据后,我可以显示currentUsers值。

您很可能是异步获取此数据的,这就是为什么出现此错误的原因。 在记录this.props.singleBase之前,您应该在控制台中看到undefined的内容。 这不会引发错误,但是如果您尝试获取未定义对象的某些属性,则会遇到此错误。 尝试记录未定义的对象是可以的,但是尝试记录该对象未定义的属性不是因为这时该对象是undefined

您可以在日志前放置一个条件:

this.props.singleBase && console.log(this.props.singleBase.currentUsers);

这是您将来要做的事情,而不是记录它们。 因此,请始终记住,如果您正在执行异步作业,则第一个渲染中将没有数据。

可能是因为您正在尝试在加载当前状态之前进行console.log 尝试在获取异步数据时设置一些标志,例如loading=true ,然后在加载后将其更改为false

const users =
    this.props.singleBase && this.props.singleBase.currentUsers !== undefined
    ? this.props.singleBase.currentUsers
    : 0;
return (
    <div>
      <h2>{users}</h2>
    </div>
);

在这里,我们确保this.props.singleBase存在且为true ,而我确保this.props.singleBase.currentUsers的值未定义。 如果两个都为真,则显示this.props.singleBase.currentUsers 关键是在异步操作完成之前,singleBase将为空。 填充数据后,我可以显示currentUsers值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM