【问题标题】:How to access redux-store from within react's componentDIdMount()如何从 react 的 componentDIdMount() 中访问 redux-store
【发布时间】:2018-08-23 09:04:08
【问题描述】:

在下面的代码中,我试图将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);

【问题讨论】:

    标签: reactjs redux react-redux redux-thunk


    【解决方案1】:

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

    【讨论】:

    • 我做的和你猜的完全一样!登录时,我将用户身份验证数据添加到 redux 商店,但它是异步的,因此在安装主屏幕时商店尚未更新。
    • 酷!我很高兴知道您发现了这个错误并修复了它。
    猜你喜欢
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2016-09-29
    相关资源
    最近更新 更多