【问题标题】:React: Uncaught TypeError: Cannot read property 'setState' of undefined反应:未捕获的类型错误:无法读取未定义的属性“setState”
【发布时间】:2018-01-20 01:15:43
【问题描述】:

我收到 Uncaught TypeError: Cannot read property 'setState' of undefined 在我连接到 Elasticsearch 的 react 项目中。

链接到我的代码: codesandbox.io/s/oq13r4vl2q

我正在尝试显示运行查询以响应 Elasticsearch 获得的结果,但我无法做到这一点。它给出了错误,但是当我在变量中运行相同的查询时,它返回了正确的结果。有人能告诉我如何将结果存储在“结果”数组中以及如何在网页中显示吗? 出现错误:

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>

        );

    }

}

【问题讨论】:

  • 错误发生在哪一行?
  • response.hits.hits.forEach(function (hit) { console.log(hit._source.text); this.setState(results: hit._source.text) }.bind(this)
  • 检查我的答案,让我知道这是否适合你。

标签: javascript reactjs elasticsearch


【解决方案1】:

我认为您正在失去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)

                )
            }
        });
    }

您可以只使用粗箭头函数来获取this 的词法绑定(我的建议)。

你要做的就是改变

 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)

                )
            }
        });

 (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)
                    });
            }
        });

【讨论】:

  • 在使用第一个解决方案时,它对 client.search 的请求不正确。我认为它没有采用“search_query”的值。
  • 第二种解决方案是否给您同样的问题?
  • POST 127.0.0.1:9200/tweet/tweet/_search?size=100 400(错误请求)从两个解决方案中获取此信息。
  • let result = client.search({ index: 'tweet', type: 'tweet', size: 100, body: { query: { match: {"text" : "new" } } , } },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); }) } } );正在返回正确的输出,但在此使用它然后给出错误
  • 您在问题中所说的原始错误解决了吗?
猜你喜欢
  • 1970-01-01
  • 2016-08-09
  • 2015-11-25
  • 2018-11-09
  • 2018-07-04
  • 1970-01-01
  • 2021-06-14
  • 2021-10-13
相关资源
最近更新 更多