Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

javascript - Error: Cannot read property 'state' of undefined, struggeling to get frontend to work

Getting this error when trying to add input from the web-application to the database. Struggeling to understad what the problem is. The error come when the button to insert to the database is used. Here's some of the code:

import React, { Component } from 'react';
import ProductService from './ProductService';


class Input extends Component {
    
    constructor(props) {
        super(props);
        this.onChangeName = this.onChangeName.bind(this);
        this.onChangeQuantity = this.onChangeQuantity.bind(this);
        this.onChangePrice = this.onChangePrice.bind(this);
        this.state = {
                id: -1,
                name: null, 
                quantity: null, 
                price: null
        };
    }

    onChangeName(e) {
        this.setState({
            name: e.target.value
        });
    }

    onChangeQuantity(e) {
        this.setState({
            quantity: e.target.value
        });
    }

    onChangePrice(e) {
        this.setState({
            price: e.target.value
        });
    }

    saveProduct() {
        var data = {
            name: this.state.name, //this is the line witch get the error
            quantity: this.state.quantity,
            price: this.state.price
        };

        ProductService.addProduct(data)
        .then(response => {
            this.setState({
                id: response.data.id,
                name: response.data.name,
                quantity: response.data.quantity,
                price: response.data.price
            });
            console.log(response.data);
        })
        .catch(e => {
            console.log(e);
        });
    }

    newProduct() {
        this.setState({
            name: "",
            quantity: null,
            price: null
        });
    }
    
    render() {
      return (
          <div id="parent">
            <form>
              <p>Enter name:</p>
              <input
                type="text"
                id="name"
                required
                value={this.state.name}
                onChange={this.onChangeName}
                name="name"
              />
            </form>
            <form>
              <p>Enter price:</p>
              <input
                type="text"
                id="price"
                required
                value={this.state.price}
                onChange={this.onChangePrice}
                name="price"
              />
            </form>
            <form>
              <p>Enter quantity:</p>
              <input
                type="text"
                id="quantity"
                required
                value={this.state.quantity}
                onChange={this.onChangeQuantity}
                name="quantity"
              />
            </form>
            <button onClick={this.saveProduct}>Enter in database</button>
          </div>
        );
    }
}

export default Input;

When i change to for example:

saveProduct() {
            var data = {
                name: "test",
                quantity: 123,
                price: 456
            };

Everything works. Ive tried diffrent things, but to me the error dont quite make sense. Anyone see where my mistake(s) are? Thank you in advance.

question from:https://stackoverflow.com/questions/65942058/error-cannot-read-property-state-of-undefined-struggeling-to-get-frontend-to

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is regarding binding this. As the ReactJS docs state:

You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.

In the constructor just add following line and your code will work:

constructor(props) {
    ...
    // This binding is necessary to make `this` work in the callback
    this.saveProduct = this.saveProduct.bind(this);
}

Do this for all event handlers. Also read the doc: https://reactjs.org/docs/handling-events.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...