如何从 react 的 componentDIdMount() 访问 redux-store

How to access redux-store from within react's componentDIdMount()

在下面的代码中,我试图将 state.userData.userDetailsredux-store 传递到 getleftpaneProductCatalogue(),但是 state.userData.userDetails 无法访问 componentDidMount()。我尝试将 state.userData.userDetails 分配给 this.prop.userProfile,但 this.prop.userProfile 仍然是一个空值。如何访问 componentDidMount 中的 prop

import React,{Component} from 'react';
import { connect } from 'react-redux';
import {Row, Col } from 'react-materialize';
import {getleftpaneProductCatalogue} from '../actions/leftpane-actions';
import ProductCatalogueLeftPaneComp from '../components/pages/product-catalogue-leftpane';

class ProductCatalogueLeftPane extends Component {
    constructor(props) {
      super(props)

    }

    componentDidMount() {
      console.log('this.props^', JSON.stringify(this.props)); 
      this.props.getleftpaneProductCatalogue().then((data) => {
        console.log('productdata', data);
      })
    }

    render() {
      return (
        <div>
            {JSON.stringify(this.props.userProfile)}

       </div>
      )
    }

  }

  const mapStateToProps = (state) => {
    console.log('state^', JSON.stringify(state));
    return {leftpaneProductCatalogue: state.leftpaneProductCatalogue, userProfile: state.userData.userDetails};
  };

  const mapDispatchToProps = (dispatch) => {
    return {
      getleftpaneProductCatalogue: () => dispatch(getleftpaneProductCatalogue()),
    };
  };

  export default connect(mapStateToProps, mapDispatchToProps)(ProductCatalogueLeftPane);

您可以直接在mapDispatchToProps中访问状态并将其传递给getleftpaneProductCatalogue:

componentDidMount() {
  const { dispatch, getleftpaneProductCatalogue }

  dispatch(getleftpaneProductCatalogue())   
}

const mapDispatchToProps = dispatch => {
  return {
    getleftpaneProductCatalogue: () => (dispatch, getState) => {
      const state = getState()
      const details = state.userData.userDetails

      return dispatch(getleftpaneProductCatalogue(details))
    },
    dispatch
  }
}

然而,你这样做的方式,通过 mapStateToProps 传递状态仍然有效,但更冗长。因此问题可能出在其他地方。

这是我的赌注。我猜你正在使用异步 API 调用在你的代码中的某处获取 userData 并且它尚未被获取。如果是这种情况 - 那么您应该首先等待数据被获取,然后您可以在组件中访问它 ProductCatalogueLeftPane.