Doubt with functions in javascript, react js

4

because when I put a function in this way, the this.state , is not bringing me the values that happened when I write in the input

fnLogin(event){
        debugger;
        event.preventDefault();
        this.setState(obtenerToken(this.state)); // this.state es marcado como undefined
        this.props.fnSetToken(this.state.token); 
    }

This is my code, when I write in the input, each input has a value in the state and it is overwritten, then I click on "NamInputEntrar" to go to the fnLogin function.

import React, { Component } from 'react'
import { Redirect } from 'react-router'
import { flogin } from '../Services/usuarios.service';
import './Estilo/Login/index.css';
import { Button , Input, CardImg} from 'reactstrap';
import obtenerToken from '../logic/obtenerToken.js';
import  {connect} from 'react-redux';
import getToken  from '../Redux/Actions.js';

class Login extends Component {  
      constructor(props){
              super(props);

              this.state = {
                redirectToReferrer: false, 
                user : "",
                password : "",
                clickOnButtonEnter: false , 
                token : ""
              };
      }

    fnLogin(event){
        debugger;
        event.preventDefault();
        this.setState(obtenerToken(this.state));
        this.props.fnSetToken(this.state.token); 
    }

    handleChangeInputs = (event) => {
        switch(event.target.name){
                  case  "NamInputUser":
                    this.setState({user: event.target.value});
                  break;

                  case  "NamInputPassword":
                    this.setState({password: event.target.value})
                  break;
                  default:
                   ;
                  break;
        }
    }

  render() { 
              const { from } = this.props.location.state || { from: { pathname: "/" } };
              const { redirectToReferrer } = this.state;

              return <div className = "container">
                            <CardImg src={require("./Imagenes/user2-512.png")} className="imgLogo" />
                            <Input type="text" value={this.state.user} onChange={this.handleChangeInputs} name = "NamInputUser" className = "NamInputUsuario" placeholder = "Usuario" />
                            <Input type="password" value={this.state.password} onChange={this.handleChangeInputs} name = "NamInputPassword"  className = "NamInputPassword"   placeholder = "Contraseña"/>
                            <Button onClick={this.fnLogin} className  = "NamInputEntrar"   color="primary">Entrar</Button>
                            <Button className = "NamInputRegis" color="secondary">Registrarme</Button>
                   </div>
  }
}

export default Login;

However, when I put the function with an arrow function, it does go to the state with all the values that I overwrote in the input.

 fnLogin = (event) => {   
            debugger;
            event.preventDefault();
            this.setState(obtenerToken(this.state));
            this.props.fnSetToken(this.state.token); 
 }

I read about the arrow function, I told myself that these do not have their own context, and I think that this is why it is easy for me to access my state object that is global, I already read about this and this one is accessing the current object should find the state, with the updated values, but I do not know what is happening.

Greetings, aiudaa!

    
asked by Francisco MS380 16.11.2018 в 20:12
source

1 answer

6

You've just stumbled upon the big difference between function( ) and ( ) => { } .

  • function( ) does not store its own this . This is obtained when invoking it, not when creating it.

  • ( ) => { } if you store your own this , which is taken from the context in which it is created.

  • The above can be seen here:

    var a = {
      nombre: 'nivel1',
      mostrar: function( ) { console.log( this.nombre ); },
      hijo: {
        nombre: 'nivel2',
        mostrar: function( ) { console.log( this.nombre ); }
      }
    }
    
    var b = a.hijo.mostrar;
    
    a.mostrar( );
    a.hijo.mostrar( );
    
    b( );
    

    Exit:

      

    level1
      level2
      undefined

    Why does calling % b( ) quit undefined ? Is not it the same as a.hijo.mostrar( ) ?

    That clearly shows how the this takes of the call , not the function or the context in which it was created.

    Regarding your question, you yourself answered:

  • Use arrow functions ( ) => { } .
  • Use function.prototype.bind( ) , which allows you to assign a this arbitrary to an invocation.

    function algo( ) { ... }
    var x = 'cucu';
    var b = algo.bind( x );
    
    b( );
    
  • answered by 16.11.2018 / 20:24
    source