使用 .map 函数在 react-multi-carousel 中加载数据会出现 'length' 未定义错误

Loading data in react-multi-carousel using .map function gives 'length' of undefined error

目前,我正在为我的轮播组件使用 react-multi-carousel,并且我正在尝试使用我的 API 数据复制此沙盒 https://codesandbox.io/s/2omn67p8kj 的第一半。我在我的 Simple.js 文件中使用 .map 从 API 映射我的数据,但我得到一个 TypeError: Cannot read 属性 'length' of undefined Currently this is my Sandbox和代码:

在我的实际项目中,我使用 getStaticProps() 来获取我的 API,但这里我包含了一个数组供参考。

沙盒:https://codesandbox.io/s/elated-firefly-446yf?file=/src/App.tsx

代码:

const responsive = {
  desktop: {
    breakpoint: { max: 3000, min: 1024 },
    items: 3,
    paritialVisibilityGutter: 60
  },
  tablet: {
    breakpoint: { max: 1024, min: 464 },
    items: 2,
    paritialVisibilityGutter: 50
  },
  mobile: {
    breakpoint: { max: 464, min: 0 },
    items: 1,
    paritialVisibilityGutter: 30
  }
};

const Simple = ({ deviceType, posts }) => {
  return (
    <Carousel
      ssr
      partialVisbile
      deviceType={deviceType}
      itemClass="image-item"
      responsive={responsive}
    >
      {posts && posts.map((image) => {
        return (
          <div>
            <Image
              draggable={false}
              style={{ width: "100%", height: "100%" }}
              src={image.Thumbnail}
            />
            <h1>{image.Title}</h1>
          </div>
        );
      })}
    </Carousel>
  );
};

export default Simple;

export async function getStaticProps() {
  const res = await fetch("http://localhost:1337/blogs");
  const posts = await res.json();

  return {
    props: { posts },
  };
}

这一行 here 可能会引发错误。

在代码 Simple.tsx 中,如果 posts 不可用,我们可能希望发送一个反应子项而不是 undefined。像这样。

{posts ? posts.map((image) => {
    return (
      <div>
        <Image
          draggable={false}
          style={{ width: "100%", height: "100%" }}
          src={image.img}
        />
        <h1>{image.Title}</h1>
      </div>
    );
  }) : <div />}