P
P
Pumba88972019-02-12 10:18:36
JavaScript
Pumba8897, 2019-02-12 10:18:36

Why isn't Redux's action being called?

Why can't I call action on button click. The error Cannot read property 'props' of undefined falls into the console . I don't understand what I'm doing wrong.

Component code:

import React, {Fragment} from 'react';
import Nav from './Nav';
import { connect } from 'react-redux';

import { Login } from '../actions/user';

class Profile extends React.Component {
    handleLogin() {
        this.props.LoginAction();
    }

    render() {
        return(
            <Fragment>
                <h1>Profile !!!</h1>
                <Nav/>
                <button onClick={this.handleLogin}>LOGIN</button>
            </Fragment>
        )
    }
}

const mapStateToProps = store => {
    return {
        isLogin: store.user.isLogin,
        isLoaded: store.content.isLoaded,
    }
}

const mapDispatchToProps = dispatch => {
    return {
        LoginAction: () => dispatch(Login())
    }
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Profile);


Reducer:

const initialState = {
    isLogin: false
}

export function userReducer(state = initialState, action) {
    switch(action.type) {
        case 'LOGIN':
            return {
                ...state, isLogin: !state.isLogin
            }
        default:
            return state
    }
}


Action I want to call:

export function Login() {
    return {
        type: 'LOGIN'
    }
}


The component sees the state from the store

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Okhotnikov, 2019-02-12
@Pumba8897

Try replacing handleLogin with an arrow function

handleLogin = () => {
        this.props.LoginAction();
    }

Or pass context via bind
onClick={this.handleLogin.bind(this)}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question