![](/img/trans.png)
[英]React-redux dispatch function with parameters from child component is undefined
[英]Pass dispatch function to child component
我正在使用redux開發通用的React應用程序。 在動作創建者中,我將數據分發給存儲。
在ComponentDidMount函數中,分派函數還可以,但是當我想將其傳遞給渲染函數中的組件時,出現錯誤: 無法讀取未定義的屬性“ dispatch”。如何將分派函數傳遞給組件?
貨櫃代碼:
class DealContainer extends React.Component {
static readyOnActions(dispatch, params) {
return Promise.all([
dispatch(DealsActions.fetchDealData(params.id)),
dispatch(SubmitActions.fetchSubmitInitialData()),
]);
}
componentDidMount() {
DealContainer.readyOnActions(this.props.dispatch,this.props.params);
}
render() {
return(
<MyComponent
changeStoreFunction = {this.props.dispatch(SubmitActions.changeUserId)}
/>)
}
const mapStateToProps = (state, ownProps) => {
return {
dealData: state.dealData,
routing: ownProps.location.query,
submitInitialData: state.submitInitialData,
id: ownProps.params.id,
mapInfo: state.mapInfo,
areaList: state.areaList,
}
};
DealContainer.propTypes = {
params: PropTypes.shape({
id: PropTypes.string.isRequired,
}).isRequired,
dispatch: PropTypes.func.isRequired,
};
}
export default connect(mapStateToProps)(DealContainer);
實際上,您需要使用mapDispatchToProps來訪問調度功能。
在那里,您可以定義將在組件render方法中調用的函數:
const mapDispatchToProps = (dispatch) => {
return {
yourFunctionToCallFromComponent: () => {
dispatch(yourAction())
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(DealContainer);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.