如何解决如何使用来自异步功能返回的React挂钩设置状态
我有一个React模块,该模块从导入的另一个JS模块中的API调用函数。该函数对后端中的烧瓶路由进行异步调用,并返回JSON对象。
setSearchData是useState。
在我的React应用程序中,我设置了SearchData(getData(searchTerm))并期望getData(searchTerm)函数将异步返回某些内容。解决我的承诺后,应通过以下方式传递jason数据:
烧瓶路线-> searchAPI异步函数->导出的API函数->通过钩子设置的状态
getsearch(search_term)-> flaskRoute(route,searchTerm)-> getSearchData(searchTerm)-> setSearchData(getSearchData(searchTerm))
这当然行不通。确实会返回JSON数据,但它永远不会更新状态。似乎该状态已用null
更新,而不必等待承诺得到解决。
如何使异步函数与本身是异步的React状态一起玩?
api_flask_routes.py
from flask import jsonify,request
@bp.route('/search/<search_term>',methods=['GET'])
def getsearch(search_term):
search_data = [
['stuff'],['stuff'],...
]
return jsonify(search_data)
SearchDataAPI.js
const flaskRoute = async (route,searchTerm="") => {
try {
const hostIPAddress = "http://127.0.0.1:5000";
const endpoint = hostIPAddress + route + searchTerm;
const configs = {
method: "GET",mode: "cors",headers: {"Content-Type": "application/json"}
}
fetch(endpoint,configs)
.then( res => res.json() )
.then( json => { return json; } ) // I return json here!
}
catch (err) {
console.log("flask route error",err);
}
};
function getSearchData(searchTerm) {
return flaskRoute("/api/search/",searchTerm); // returns json to importing module
}
MySearch.js,这是一个React组件
import searchDataAPI from '../searchAPI/SearchDataAPI';
//// DATA RETRIEVAL FROM BACKEND ////
const [searchData,setSearchData] = useState(null);
const getSearchData = searchDataAPI.searchFunctions.getSearchData;
function handleSubmitSearch(e) {
e.preventDefault();
if (searchTerm.trim().length > 0) {
setSearchData(null); // clears out previous search data
setSearchData(getSearchData(searchTerm)); // this doesn't work!
// more stuff...
}
}
解决方法
您必须等待使用.then()的函数解析,如下所示:
getSearchData(searchTerm).then(result => {
setSearchData(result)
});
如果仍然返回null,则必须将getSearchData()更改为异步,因此它还可以返回解析结果,如:
async function getSearchData(searchTerm) {
return await flaskRoute("/api/search/",searchTerm).then(res => {
return res;
});
}
如果这还是行不通的,您可以直接在getSearchData()中设置setState:
function getSearchData(searchTerm) {
flaskRoute("/api/search/",searchTerm).then(result => {
setSearchData(result);
});
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。