使用axios,我调用了一个Mongo REST API。但是,每当我按下绑定到它上的按钮时,我都会得到这样的错误:
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()方法中,就不会有任何问题。
我的类是这样设置的:
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 RecipeBuilderSearchBar组件的设置如下:
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可以在这里看到:
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()的工作版本(但是我不知道为什么):
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
})
}发布于 2020-04-29 07:04:37
您的search_elastic函数不返回任何内容。它需要返回来自axios.get()的承诺。
// 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
})
}https://stackoverflow.com/questions/61491396
复制相似问题