gpt4 book ai didi

javascript - 类型错误 : Cannot read property 'then' of undefined - React Hooks

转载 作者:行者123 更新时间:2023-11-30 19:12:14 25 4
gpt4 key购买 nike

我是 React 的新手,我正在创建一个网站,用户可以在其中搜索查询并显示结果。

我有一个名为:Searchbar的组件,它包含两个功能:

1)用户编写一个查询,当用户按下回车键时,该查询通过 axios POST 请求发送到后端。

2) 后端搜索相关query,并通过axios GET请求返回结果。

因此顺序是:postQuery()-->getQueryResult() 所以我认为 postQuery() 创建了一个 promise ,如果解决了,允许 getQueryResult() 运行。但是我得到:

TypeError: Cannot read property 'then' of undefined

Error on line 38: return postQuery(query).then(() => getQueryResult());

我的代码是:

function Searchbar() {

const [query, setQuery] = useState("");
const [results, setResults] = useState(["myemptyinitiallist"]);

function postQuery(query) {
var myParams = {
data: query
}
axios.post('http://localhost:5000/api/query', myParams)
.then(function(response){
console.log("Yes, it sends the query in JSON format to Flask");
})
.catch(function(error){
console.log(error, "Error on AXIOS post");
});
} // Enf of postQuery

function getQueryResult() {
(axios.get('http://localhost:5000/api/query')
.then(function (response) {
setResults(response.data); //set the value
console.log(results)
}))
} // End getQueryResult()

function handleEnter(query){
if (query != "") {
return postQuery(query).then(() => getQueryResult());
} else {
alert("The search query cannot be empty")
}
} // End of function handleEnter()


return(
<div>
<SearchBar
onChange={(event) => setQuery(event)}
onRequestSearch={() => handleEnter(query)}
style={{
marginTop: 200,
marginLeft: 'auto',
marginRight: 'auto',
maxWidth: 800,
}}
/>
<ResultList/>
</div>
)
}


export default Searchbar;

最佳答案

postQuery 中没有 return 语句,因此它返回 undefined。此外,catch 子句默认履行其返回的 promise 。要允许返回 promise 也被捕获,请在 catch 回调中重新抛出错误。

尝试

  function postQuery(query) {
var myParams = {
data: query
}
return axios.post('http://localhost:5000/api/query', myParams)
.then(function(response){
console.log("Yes, it sends the query in JSON format to Flask");
})
.catch(function(error){
console.log(error, "Error on AXIOS post");
throw error; // don't fulfill returned promise
});
} // End of postQuery

关于javascript - 类型错误 : Cannot read property 'then' of undefined - React Hooks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58359781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com