搜索栏触发但没有更改生效 - 反应钩子



我正在尝试使用搜索组件进行搜索过滤器 Ant.Design 我仔细遵循了他们的文档,但它触发并且 searchQuery 状态发生变化,但没有任何反应。

同样在我的控制台中,我可以看到它触发了两次,因此它被记录了 2 次,我不知道为什么。

任何帮助将不胜感激。

import React, { useEffect, useState } from "react";
import axios from "axios";
import { Layout, Loading } from "../components";
import { Table, Input, Button, Space } from "antd";
import { set } from "react-ga";
// import config from '../config.json';
const { Search } = Input;
const Overview = () => {
const [loading, setLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState("");
const [devices, setDevices] = useState([]);
const columns = [
{
title: "Name",
dataIndex: "name",
key: "name",
},
{
title: "Type",
dataIndex: "username",
key: "username",
},
{
title: "Balance",
dataIndex: "phone",
key: "phone",
},
{
title: "Status",
dataIndex: "website",
key: "website",
},
{
title: "",
dataIndex: "",
key: "website",
},
];
useEffect(() => {
async function callApi() {
const response = await axios.get(`https://jsonplaceholder.typicode.com/users`);
const devices = response.data;
setDevices(devices);
// const response = await axios.get(`${config.serverAPI}/devices`);
// const devices = response?.data?.status === 'success' && response?.data?.devices;
// console.log("Devices", devices);
await localStorage.setItem("devices", JSON.stringify(devices));
setLoading(false);
}
callApi();
}, [searchQuery]); // eslint-disable-line react-hooks/exhaustive-deps
return (
<Layout>
<div className="overview-page-wrapper">
{loading ? (
<Loading />
) : (
<div>
<Search
placeholder="Search for devices"
value={searchQuery}
onChange={(e) => {
const currSearchValue = e.target.value;
setSearchQuery(currSearchValue);
const filteredDevices = devices.filter((device) => device.name.toLowerCase().includes(currSearchValue));
setDevices(filteredDevices);
}}
/>
{console.log(searchQuery)}
<div>
<Table columns={columns} dataSource={devices} />
</div>
</div>
)}
</div>
</Layout>
);
};
export default Overview;

尝试尽可能少地修改代码。我会说 3 个变化

1 - 从第一个效果中删除searchQuery依赖项

useEffect(() => {
async function callApi() {
const response = await axios.get(`https://jsonplaceholder.typicode.com/users`);
const devices = response.data;
setDevices(devices);
// const response = await axios.get(`${config.serverAPI}/devices`);
// const devices = response?.data?.status === 'success' && response?.data?.devices;
// console.log("Devices", devices);
await localStorage.setItem("devices", JSON.stringify(devices));
setLoading(false);
}
callApi();
}, []); // eslint-disable-line react-hooks/exhaustive-deps

2 - 添加filterdDevices状态和效果

const [filterdDevices, setFilteredDevices] = useState([]);
useEffect(() => {
const filtered = devices.filter(device =>
device.name.toLowerCase().includes(searchQuery)
);
setFilteredDevices(filtered);
}, [searchQuery, devices]);

3 - 简化选择组件的onChange

<Search
placeholder="Search for devices"
value={searchQuery}
onChange={e => {
const currSearchValue = e.target.value;
setSearchQuery(currSearchValue);
}}
/>

相关内容

  • 没有找到相关文章

最新更新