繁体   English   中英

React array.length 返回 0 即使数组有项目

[英]React array.length returning 0 even though array has items

我正在使用 Firestore 从我的数据库中提取内容。 当我登录到拉取数据的 function 时,数组中有数据。 当我登录我的主要组件时,它也有。 但由于某种原因,.map 不起作用,当我尝试 array.length 时它返回 0。我使用的是 map,但后来我将其更改为使用 function 以尝试获取错误。

export default function Search() {
  const [searchedData, setSearchedData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [noBook, setNoBook] = useState(false);
  const [showBooks, setShowBooks] = useState(false);

  const link = useLocation();
  useEffect(() => {
    const srch = link.pathname.substring(8);
    loadSearchBooks(srch);
  }, [link]);

  async function loadSearchBooks(srch) {
    try {
      const bookArray = await getSearchedBooks(srch);
      bookArray ? setShowBooks(true) : setNoBook(true);
      setSearchedData(bookArray);
    } catch (e) {
      setSearchedData(null);
    } finally {
      setLoading(false);
    }
  }

  function renderBooks() {
    console.log(searchedData);
    const l = searchedData.length;
    return l;
  }

  return (
    <div>
      <Navbar />
      <div className={searchBookWrapper}>
        {loading && 'Carregando'}
        {showBooks && renderBooks()}
        {noBook && <BookCardItem />}
      </div>
    </div>
  );
}

执行此操作时,console.log(searchedData) 返回数组,但 const l = searchedData.length 仅显示 0。当我再次搜索时,数字在即将更改时暂时变为 12。 这是以前的代码:

  return (
    <div>
      <Navbar />
      <div className={searchBookWrapper}>
        {loading && 'Carregando'}
        {showBooks &&
          searchedData.map(({ afn, aln, notes, quant, title }, index) => {
            return (
              <BookCardItem
                key={title}
                firstName={afn}
                lastName={aln}
                notes={notes}
                quant={quant}
                title={title}
                bookNumber={index}
              />
            );
          })}
        {noBook && <BookCardItem />}
      </div>
    </div>
  );
}

同样的事情发生了。 当我再次搜索时,bookInfo 只出现了一会儿。

从这个问题的第一个代码开始,这是控制台:

控制台 - 一个空数组,然后是两个填充数组

如果 useLocation 是 API 调用或其他异步 function,则 React 更喜欢将它们放在 useEffect 中。 如果不是,它会给出不一致的结果。 尝试将 useLocation 放在 useEffect 中。 如果您只计划 useLocation 触发一次(因此 loadSearchedBooks 只触发一次),您甚至可以将它们放在同一个 useEffect 中,只是不要让它们根据它们更新的内容重新呈现。

useEffect(() => {
  useLocation().then(link => {
  const srch = link.pathname.substring(8);
  loadSearchBooks(srch);
    }
  }, []);

希望这可以解决您的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM