javascript - 搜索栏对调用数据表做出反应
问题描述
我正在尝试在反应中创建一个搜索栏,该搜索栏从当前视图内的 API 创建一个数据表。
async function handleSearch() {
console.log("searching...", searchRef.current?.value);
setMessage("Searching...");
var headers = {
"Content-Type": "application/x-www-form-urlencoded",
"auth-token": token,
};
fetch(
"http:"..
{
method: "GET",
headers: headers,
}
)
.then((response) => {
setMessage("");
if (response.status !== 200) {
console.log("erROR", response);
return null;
} else {
console.log("success", response);
this.searched = true;
let productList = response.json()
return productList;
}
})
.then((responseData) => {
console.log("responseData", responseData);
// setting resonseData to productList
setProductList(responseData);
});
}
出于某种原因,这很难得到工作。
我想上面的代码可以工作并用正确的数组填充表格,但事实并非如此。
JSON 响应是这样的,并且当前在带有搜索组件的控制台中正常工作。
关于如何解决这个问题的任何想法?
解决方案
看来您需要将productList添加为状态变量,如下所示。
// We need to initialize with empty array. Otherwise while rendering component for the first time it will try to access map of undefined(productList).
const [productList,setProductList] = useState([]);
// And then in your fetch call you can store data inside productList
fetch(
"http://localhost:5000/adverts/mwap?searchTerm=" +
encodeURIComponent(searchRef.current.value),
{
method: "GET",
headers: headers,
}
)
.then((response) => {
setMessage("");
if (response.status !== 200) {
console.log("erROR", response);
return null;
} else {
console.log("success", response);
this.searched = true;
let productList = response.json()
return productList;
}
})
.then((responseData) => {
console.log("responseData", responseData);
// setting resonseData to productList
setProductList(responseData);
});
推荐阅读
- installation - fedora 的安装:没有任何反应
- hybris - 客户将可选配置文件加载到 hybris
- html - 需要帮助修改自定义下拉菜单并更改其值
- javascript - 为什么 forEach 函数在这里给出错误“无法读取未定义的属性 'forEach'”?
- html - Chrome 内置 PDF 查看器的自定义标题
- android - xxx 0 未知错误的 Http 失败响应
- c# - 设置父类变量并将其放入子类c#
- docker - 当我启动`docker compose up`时,如何解决“权限被拒绝”的问题?
- java - 一次为所有客户端定义 /mp-rest/url Quarkus YAML
- postgresql - 在组内添加唯一的行