【问题标题】:How to only render something once at a specific index of an Array. React native如何只在数组的特定索引处渲染一次。反应原生
【发布时间】:2020-05-14 20:13:13
【问题描述】:

所以本质上,我的问题源于试图解决这个问题。

function SwiperComponent () {

  const [item, setItems] = useState([["hi",console.log("hi")], ["hello",console.log("hello")], ["never",console.log("never")], ["sorry",console.log("sorry")]])
  const swiperItems = item.map(ite => {
    return(
        <View style={styles.slide1} >
          <Text style={styles.text}>{ite[0] + ite[1]}</Text>
        </View>
    )
  })
    return (
        <Swiper
            key={item.length}
            style={styles.slide1}
        >
          {swiperItems}
        </Swiper>
    )

}

所以我的代码相当简单,我使用 React-Native-Swiper 库,本质上使数组中的视图可滑动。

现在的问题是,当我运行代码时,它会同时生成数组中的所有视图,我知道这一点是因为我可以在控制台中看到,打印语句都在启动时打印出来。随之而来的问题是,如果我有一长串的图片,我不想一次检索所有这些图片,因为它会降低性能,但显然用户不去的可能性很大通过所有图像,在这种情况下,我将调用我的服务器以不必要地检索图像(我正在使用 firebase,因此我试图限制成本问题)。

那么,只有在我开始滑动后,靠近它们时,如何才能渲染这些图像?

【问题讨论】:

  • console.log 返回undefined,所以我真的不明白你在这里要做什么?
  • 对于渐进式加载,React-Native-Swiper 文档中有一个LoadMinimal example
  • 老实说,仔细想想,这可能只是一个后端问题。 Prolly 与反应无关,我还是把这个帖子留在上面,以防万一这可以在前端以某种方式解决。对不起我的愚蠢我是初学者。
  • 谢谢 Emile,我会调查的!

标签: javascript reactjs react-native react-native-swiper


【解决方案1】:

您应该可以在 react-native-swiper 中使用 loadMinimal 设置。

这里,你需要通过设置loadMinimalSize来指定loadMinimal为true以及当前幻灯片前后需要加载的幻灯片数。

<Swiper
  key={item.length}
  style={styles.slide1}
  loadMinimal={true} // only loads the current page + [loadMinimalSize] amount of pages before and after
  loadMinimalSize={0}
  loadMinimalLoader={() => (
    <View>
      <Text>Loading</Text>
    </View>
  )} // optional loader to show while page loads
>
  {swiperItems}
</Swiper>

或者,您可以使用延迟加载图像库,该库仅在您在阈值内滚动时才加载图像。 https://github.com/Aljullu/react-lazy-load-image-component.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 1970-01-01
    • 2022-11-07
    相关资源
    最近更新 更多