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

时间:2018-08-23 09:04:08

标签: reactjs redux react-redux redux-thunk

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

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);

1 个答案:

答案 0 :(得分:2)

您可以直接在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中访问它。