无法在ReastJS useEffect挂钩中清空数组

时间:2020-07-30 14:34:09

标签: javascript arrays reactjs

我在React中有此表视图,我从API那里获取一个数组并显示它。当用户在表格搜索框上键入内容时,我正在尝试清除当前状态数组并呈现全新的结果。但是由于某种原因,结果会不断添加到当前结果集之后。

这是我的代码:

const Layout = () => {

  var infiniteScrollTimeout = true;
  const [apiList, setapiList] = useState([]);

  //invoked from child.
  const search = (searchParameter) => {
    //Clearing the apiList to load new one but the console log after setApiList still logs the old list
    setapiList([]); // tried setApiList([...[]]), copying the apiList to another var and emptying it and then setting it too.
    console.log(apiList); //logs the old one.
    loadApiResults(searchParameter);
  };

  let url =
    AppConfig.api_url + (searchParameter || "");

  const loadApiResults = async (searchParameter) => {

    let response = await fetch(url + formurlencoded(requestObject), {
      method: "get",
      headers: headers,
    });
    let ApiResult = await response.json(); // read response body and parse as JSON

    if (ApiResult.status == true) {
      //Set the url for next fetch when user scrolls to bottom.
      url = ApiResult.next_page_url + (searchParameter || "");

      let data;
      data = ApiResult.data;

      setapiList([...data]);
    }
  }

  useEffect(() => {
    loadApiResults();

    document.getElementById("myscroll").addEventListener("scroll", () => {
      if (
        document.getElementById("myscroll").scrollTop +
          document.getElementById("myscroll").clientHeight >=
        document.getElementById("myscroll").scrollHeight - 10
      ) {
        if (infiniteScrollTimeout == true) {
          console.log("END OF PAGE");
          loadApiResults();
          infiniteScrollTimeout = false;
          setTimeout(() => {
            infiniteScrollTimeout = true;
          }, 1000);
        }
      }
    });
  }, []);


  return (
    <ContentContainer>
      <Table
        ...
      />
    </ContentContainer>
  );
};
export default Layout;

我在做什么错了?

更新:在重置状态后再次调用loadApiResult时,我确实看到了重置状态的一小会儿。旧的状态又回来了。如果我删除对loadApiResult的调用,则表呈现将保持空白。

2 个答案:

答案 0 :(得分:0)

在数组中添加apiList作为useEffect中的第二个参数

答案 1 :(得分:0)

您需要在useEffect函数中使用dependencies feature

const [searchParameter, setSearchParameter] = useState("");
... mode code ...

useEffect(() => {
  loadApiResults();

  ... more code ...
}, [searchParameter]);

useEffect会在searchParameter的值更改时自动触发,假设您的输入在更改时使用setSearchParameter