![](/img/trans.png)
[英]ReferenceError: Cannot access 'UserContext' before initialization - React
[英]HOC React and Redux : Cannot access 'mapStateToProps' before initialization
我想制作用redux
包裹的高階組件/ HOC
我試過這樣的事情:
export const Button = connect(mapStateToProps,mapDispatchToProps)(
() => {
return(
<Link
to="#"
className="btn-enter"
onClick={() => this.props.handleShare()}>
Undang Teman
</Link>
);
});
const mapStateToProps = (state) => {
}
const mapDispatchToProps = (dispatch) => {
return {
handleShare: () => dispatch({type: ActionType.HANDLE_SHARE_MODAL})
}
}
但是當我運行此代碼時,我收到消息錯誤:
ReferenceError:初始化前無法訪問“mapStateToProps”
正如它所說,您應該首先初始化函數以稍后訪問它,因此它必須是
const mapStateToProps = (state) => {
}
const mapDispatchToProps = (dispatch) => {
return {
handleShare: () => dispatch({type: ActionType.HANDLE_SHARE_MODAL})
}
}
export const Button = connect(mapStateToProps,mapDispatchToProps)(
() => {
return(
<Link
to="#"
className="btn-enter"
onClick={() => this.props.handleShare()}>
Undang Teman
</Link>
);
});
此外,如果您不需要mapStateToProps
您可以將其保留為null
// Better to declare component above and then pass it to connect HOC
const ButtonComponent = (props) => {
return(
<Link
to="#"
className="btn-enter"
// ButtonComponent is a functional component
// and to you props you get them from params
onClick={() => props.handleShare()}>
Undang Teman
</Link>
);
}
const mapDispatchToProps = (dispatch) => {
return {
handleShare: () => dispatch({type: ActionType.HANDLE_SHARE_MODAL})
}
}
export const Button = connect(null, mapDispatchToProps)(ButtonComponent);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.