首页 > 解决方案 > 从 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);

标签: javascriptreactjs

解决方案


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.


推荐阅读