在以下代码中,我尝试将state.userData.userDetails
从redux-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);
答案 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
中访问它。