javascript - 从 componentDidMount 方法访问道具状态给出未定义
问题描述
您好,我是 react 和 redux 的新手,我正在尝试从 componentDidMount 方法访问商店,但总是给我 undefined,当控制台从 mapActionToState 第一次给我 undefined 然后给我真实状态时
import React, {Component} from 'react'
import {connect} from "react-redux";
class UserProperties extends Component {
constructor(props) {
super(props);
this.state = {
tabs: {
published: true,
drafts: false,
pending: false,
rejected: false
}
}
}
componentDidMount() {
document.title = "Add Property | Real Estate";
console.log(this.state)
}
render() {
return (
<div>
</div>
)
}
}
let mapStateToProps = state => {
console.log(state)
return state.user
};
export default connect(mapStateToProps)(UserProperties);
解决方案
redux 状态被注入到你的 props 中,所以为了在你的 componentDidMount 中访问它,你需要记录this.props
而不是this.state
. 请注意,mapStateToProps
期望Object
键对应于道具中的键的位置。这意味着如果你state.user
看起来像
{
name: 'Name',
role: 'administrator'
}
然后使用您当前的代码,您会发现您的道具分别具有两个this.props.name
属性this.props.role
。
写这个的更好的方法是
const mapStateToProps = state => {
console.log(state)
return {user: state.user}
};
之后您的用户对象可以作为this.props.user
.
推荐阅读
- c# - 具有不同数据库的通用数据访问类
- jquery - 保护登录后页面免受未经授权的访问 - jQuery + Java Spring
- modeling - 在空间中离散 PDE 以与 modelica 一起使用
- c# - Unity 的 MonoBehaviour 类中的“消息”是什么?(开始,更新,唤醒...等)
- netsuite - NetSuite Script 2.0 如何在报价单上禁用行项目上的金额字段
- sed - 使用 sed 合并行
- android - 将图像从半屏滚动到全屏,将内容向下移动
- node.js - 使用 Promise 在 Node.js 中调用异步递归函数
- javascript - 使用 vuejs 从输入中动态添加项目
- python - 用于从维基百科中的 ParserFunctions 生成值的 Python 工具/库