【问题标题】:Search Bar fires but no changes take effect - React Hooks搜索栏触发但没有更改生效 - React Hooks
【发布时间】:2020-06-23 11:39:45
【问题描述】:

我正在尝试使用 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;

【问题讨论】:

    标签: javascript reactjs react-hooks antd


    【解决方案1】:

    尝试尽可能少地修改您的代码。我会做出 3 个改变

    1 - 从第一个 Effect 中删除 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 - 在 Select 组件上简化 onChange

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

    【讨论】:

      猜你喜欢
      • 2019-07-22
      • 1970-01-01
      • 2020-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      相关资源
      最近更新 更多