简体   繁体   中英

HOC React and Redux : Cannot access 'mapStateToProps' before initialization

I want make higher-order component / HOC wrapped with redux

I tried something like that :

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

But when i run this code i got message error :

ReferenceError: Cannot access 'mapStateToProps' before initialization

as it says you should first initialize function to access it later so it must be

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

Also if you don't need mapStateToProps you can leave it as 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM