Why do I get the message from Property is Undefined even with Arrow Function?

Asked

Viewed 49 times

0

I’m starting with React and can not understand why the code below does not work. I receive the following message: "Typeerror: can’t access Property "aoClicarNota", this is Undefined"

I’m already using aoClicarNota as Arrow Function but it still doesn’t work. What am I doing wrong?

import React from 'react';
import axios from 'axios';
import { Button, ButtonGroup, Container } from 'react-bootstrap';

class BlocoNotasPossiveis extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            notasPossiveis: [
                {
                    nota: '1',
                    descricaoCurta: 'Nota baixa',
                    descricaoLonga:
                        'Serviços sempre apresentam falhas, com grande impacto na produtividade, gerando retrabalho constantemente.'
                },
                {
                    nota: '2',
                    descricaoCurta: 'Nota ruim',
                    descricaoLonga:
                        'Serviços sempre apresentam falhas, com grande impacto na produtividade, gerando retrabalho constantemente.'
                }
            ]
        };
    }

    render() {
        return (
            <div className="sombra">
                <ButtonGroup aria-label="First group">
                    {this.state.notasPossiveis.map(this.renderizarBotao)}
                </ButtonGroup>
            </div>
        );
    }

    aoClicarNota = () => {
        console.log("valor.nota")
    }

    renderizarBotao(valor) {
        return (
            <Button variant="primary" size="lg" onClick={this.aoClicarNota}>
                <span className="linhaNumeral">{valor.nota}</span>
                <span className="linhaDescricaoCurta">{valor.descricaoCurta}</span>
            </Button>
        );
    }
}

export default BlocoNotasPossiveis;
  • When you use class component in React, you need to bind the function within the constructor. In your case, try to place this.aoClicarNota = this.aoClicarNota .bind(this); and see if it works.

  • @Colasanto Unfortunately it didn’t work by making the bind in the builder. grateful.

1 answer

2


The problem lies in its function renderizarBotao. Inside it, you try to access this.aoClicarNota, but there is no this defined in the context of the function renderizarBotao.

We need to define a this for its function renderizarBotao and we can do this in two ways:

  1. Make the bind manually from: this.renderizarBotao = this.renderizarBotao.bind(this); in the class builder;
  2. Use the syntax of arrow function for this function also renderizarBotao = (valor) => {

Here an example implementing arrow function: https://codesandbox.io/s/react-playground-gp6io

Browser other questions tagged

You are not signed in. Login or sign up in order to post.