首页 > 解决方案 > 搜索栏对调用数据表做出反应

问题描述

我正在尝试在反应中创建一个搜索栏,该搜索栏从当前视图内的 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 响应是这样的,并且当前在带有搜索组件的控制台中正常工作。

关于如何解决这个问题的任何想法?

标签: javascriptreactjsnext.js

解决方案


看来您需要将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);
  });

推荐阅读