首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ReactJS -将.then添加到函数会使"this.state.searchText“无效

ReactJS -将.then添加到函数会使"this.state.searchText“无效
EN

Stack Overflow用户
提问于 2020-04-29 07:00:34
回答 1查看 42关注 0票数 0

使用axios,我调用了一个Mongo REST API。但是,每当我按下绑定到它上的按钮时,我都会得到这样的错误:

代码语言:javascript
复制
TypeError: Object(...)(...) is undefined
onSearchButtonPressed
D:/foo/hello-world/src/RecipeBuilder.js:146

> 146 |     search_elastic(this.state.searchText).then({
      | ^  147 | 
  148 |     })
  149 | 

为什么会发生这种情况?如果我在不附加then的情况下调用search_elastic,它似乎可以工作,但是没有返回任何数据。更有趣的是,如果我删除search_elastic方法的封装,并将axios.get代码块直接插入到onSearchButtonPressed()方法中,就不会有任何问题。

我的类是这样设置的:

代码语言:javascript
复制
import React, { Component } from 'react'
import {search_elastic, shell} from './Backend.js'

class RecipeBuilder extends Component {
    constructor(props) {
        super(props);
        this.state = {
            id: '',
            term: '',
            editDisabled: false,
            ingredients: [],
            candidates: [],
            searchText: '',
            searchResults: []
        }
        this.onSearchTextChange = this.onSearchTextChange.bind(this)
        this.onSearchButtonPressed = this.onSearchButtonPressed.bind(this)
    }
    onSearchTextChange(filterText) {
        console.log({filterText})
        this.setState({
            searchText: filterText
        });
    }
    onSearchButtonPressed() {
        search_elastic(this.state.searchText).then(data => {
            //ideally would like to add data from this method to the RecipeBuilder state

        })
    }
    render () {
        return (
            <div className="col-md-12">
                    <SearchBar
                      searchText={this.state.searchText}
                      onSearchTextChange={this.onSearchTextChange}
                      />
                      <button onClick={this.onSearchButtonPressed}>Search</button>
            </div>
            )
    }
}
export default RecipeBuilder

SearchBar组件的设置如下:

代码语言:javascript
复制
class SearchBar extends Component {
    constructor(props) {
        super(props);
        this.handleSearchTextChange = this.handleSearchTextChange.bind(this);
    }

    handleSearchTextChange(e) {
        this.props.onSearchTextChange(e.target.value);
    }

    render() {
        return (
            <div>
            <form>
                <input
                 type="text"
                 placeholder="Search..."
                 value={this.props.searchText}
                 onChange={this.handleSearchTextChange}
                />
            </form>
            </div>
        );
    }
}

Backend.js可以在这里看到:

代码语言:javascript
复制
import axios from 'axios'


export const search_elastic = term => {
    axios
        .get(`api/search/${term}`, {
            headers: { 'Content-type': 'application/json' }
        })
        .then((response) => {
            console.log(response)
            return response
        })
}

export const shell = () => {
    console.log("In shell")

}

onSearchButtonPressed()的工作版本(但是我不知道为什么):

代码语言:javascript
复制
    onSearchButtonPressed() {
        axios.get(`api/search/${this.state.searchText}`, {
                headers: { 'Content-type': 'application/json' }
            }).then((response) => {
                //console.log(response)
                if (response != null) { 
                    var data = response["data"]
                    var result = data["result"]
                    var hitsObj = result["hits"]
                    var hitsArray = hitsObj["hits"]
                    this.setState({searchResults: [...hitsArray]})
                    console.log(this.state.searchResults)
                }
                return response
            })
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-29 07:04:37

您的search_elastic函数不返回任何内容。它需要返回来自axios.get()的承诺。

代码语言:javascript
复制
// either *return* axios.get or remove the curlies for an implicit arrow function return
export const search_elastic = term => {
  return axios
    .get(`api/search/${term}`, {
      headers: { 'Content-type': 'application/json' }
    })
    .then((response) => {
      console.log(response)
      return response
    })
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61491396

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档