简体   繁体   中英

React: Uncaught TypeError: Cannot read property 'setState' of undefined

I'm getting Uncaught TypeError: Cannot read property 'setState' of undefined in my react project which I'm connecting to Elasticsearch.

Link to my code: codesandbox.io/s/oq13r4vl2q

I'm trying to display result which I get from running the query in react for Elasticsearch but I'm unable to do that. It's giving error but when I am running the same query in a variable it returning the currect result. Can someone please tell me how to store the result in the "results" array and how to display that in the webpage? Getting error on this:

import React, { Component } from 'react';
import client from './Credentials';
import '../App.css';
import DisplayResult from './DisplayResult';
export default class Search extends Component {

    constructor(props) {
        super(props);

        this.state = {results: []};
    }

    handleChange(event) {
        const search_query = event.target.value;

        client.search({
            index: 'tweet',
            type: 'tweet',
            size: 100,
            body: {
                query: {
                    match: search_query
                },
            }
        }, function (error, response, status) {
            if (error) {
                console.log("search error: " + error)
            }
            else {
                console.log("--- Response ---");
                // console.log(response);
                console.log("--- Hits ---");
                response.hits.hits.forEach(function (hit) {
                        console.log(hit._source.text);
                        this.setState(results: hit._source.text)
                    }.bind(this)

                )
            }
        });
    }




    render() {

        return(

            <div>
                <input className={"search-bar"} type="text" onChange={this.handleChange}>
                </input>
                <DisplayResult results={this.state.results} />
                {/*<button className={"button"}><Search /></button>*/}

            </div>

        );

    }

}

I think you're losing the context of this . You can either format your code like this.

import React, { Component } from 'react';
import client from './Credentials';
import '../App.css';
import DisplayResult from './DisplayResult';
export default class Search extends Component {

    constructor(props) {
        super(props);

        this.state = {results: []};
    }

    handleChange(event) {
        let _this = this;
        const search_query = event.target.value;

        client.search({
            index: 'tweet',
            type: 'tweet',
            size: 100,
            body: {
                query: {
                    match: search_query
                },
            }
        }, function (error, response, status) {
            if (error) {
                console.log("search error: " + error)
            }
            else {
                console.log("--- Response ---");
                // console.log(response);
                console.log("--- Hits ---");
                response.hits.hits.forEach(function (hit) {
                        console.log(hit._source.text);
                        _this.setState(results: hit._source.text)
                    }.bind(this)

                )
            }
        });
    }

OR

You can just use fat arrow functions to pick up the lexical binding of this (my recommendation).

All you have to do is change

 function (error, response, status) {
            if (error) {
                console.log("search error: " + error)
            }
            else {
                console.log("--- Response ---");
                // console.log(response);
                console.log("--- Hits ---");
                response.hits.hits.forEach(function (hit) {
                        console.log(hit._source.text);
                        _this.setState(results: hit._source.text)
                    }.bind(this)

                )
            }
        });

TO

 (error, response, status) => {
            if (error) {
                console.log("search error: " + error)
            } else {
                console.log("--- Response ---");
                // console.log(response);
                console.log("--- Hits ---");
                response.hits.hits.forEach(function (hit) {
                        console.log(hit._source.text);
                        this.setState(results: hit._source.text)
                    });
            }
        });

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