【问题标题】:Getting error of fetched items after refreshing the page刷新页面后获取项目错误
【发布时间】:2021-12-11 03:09:00
【问题描述】:

我照常从外部 API 获取数据,这是我的典型做法:

获取 API:

 const [tshirts, setTshirts] = useState([]);

    const fetchData = () => {
        fetch('apiEndpoint')
            .then((response) => response.json())
            .then((data) => {
                setTshirts(data[0].clothes.regular.top); // path to my array
            })
            .catch((error) => {
                console.log(error);
            });
    };
    React.useEffect(() => {
        fetchData();
    }, []);

通过数组映射:

const tshirtArray = tshirts.tShirt; // specifying the path
const listItems = tshirtArray.map((item) => <li>{item}</li>);

<ul>{listItems}</ul>

数据结构示例:

[
  {
  id: 1,
  clothes: {
     regular: {
      top: {
        sleeveless: [],
        tShirt: [
          "image-path-here"
          ],
.....
.....
.....

当我第一次执行代码时,它可以工作,但一段时间后或刷新页面后,我收到错误 TypeError: Cannot read properties of undefined (reading 'map')

为什么没有定义?路径是正确的,获取数组也应该是正确的。找不到它不工作的原因。

【问题讨论】:

  • tshirts 最初是数组,所以不能取tshirts.tShirt
  • @sojin 但我还能如何从数组中获取项目
  • 你删除了另一个问题,所以我在这里评论:你有&lt;Component /&gt;,即根本没有传递任何道具。

标签: javascript arrays reactjs react-hooks fetch


【解决方案1】:

我没有评论的声誉,所以让我尝试通过答案为您澄清。正如@sojin 提到的,你不能使用 tshirts.Tshirt 因为你的状态是数组类型并且数组不能像对象一样使用,这意味着如果有一个对象可以说 exampleObject = { type: "shirt", color: "你可以用 exampleObject.type 来调用它。因为你的状态中有一个对象数组(你保存到状态的顶部仍然是包含 tShirt 数组的对象),你首先必须使用索引(告诉你哪个对象想要从状态数组中使用)然后你可以像你想要的那样使用它。例如,在你的例子中,状态数组中有 1 个对象。数组索引从 0 开始。所以你可以做 tshirts[0].tShirt 来获得该对象的 tShirt 数组。

不过,我会稍微修改一下您的代码。而不是使用 tshirtArray 常量,只需从您的状态执行 listItems :

const listItems = tshirts.map((item) =>

  • {item.tShirt[0]}
  • );

    注意:我刚刚在这里使用了索引 0 来演示在 tShirt 数组中找到第一项。如果您想查看所有 tShirt 图像路径,那么您可能需要进行嵌套映射或其他类似的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-19
      • 2012-05-13
      • 2012-10-24
      • 2013-07-18
      • 2018-04-03
      • 2021-11-03
      • 1970-01-01
      • 2013-07-05
      相关资源
      最近更新 更多