1

我有一个头像组件,里面有以下 XML

    <Image
      source={avatars && avatars[deferredKey]
        ? { uri: avatars[deferredKey] } : defaultAvatar}
      style={{
        width: size, height: size, borderRadius: size / 2, ...containerStyle,
      }}
      onError={this.onError}
    />

当应用程序加载头像时为空,因此 defaultAvatar 加载,然后几秒钟后图像接收到新的道具,它应该切换到 uri 图像,但它无法做到这一点。

当我将代码更改为

   <Image
      source={{ uri: avatars[deferredKey] }}
      style={{
        width: size, height: size, borderRadius: size / 2, ...containerStyle,
      }}
      onError={this.onError}
    />

然后组件按预期工作,最初头像加载空白,几秒钟后它正确加载 uri 图像。

该问题似乎仅在头像必须从本地存储的资产切换到 uri 时才存在。

4

2 回答 2

0

我在这里找到了答案,https://github.com/facebook/react-native/issues/9195。似乎它本质上是一个 react-native Image 错误并且已经有一段时间了。

根据规范,你应该能够做这样的事情

<Image source={{uri : myImage, cache: 'reload'}} />

但即使这样也行不通。

事实证明,自 2016 年以来一直在工作的最佳解决方案实际上是向您的 Image 组件添加一个键,该键指向 state 中的源值:

key={this.state.source.uri}
于 2020-07-02T10:38:14.260 回答
0

像往常一样,我为此奋斗了 2 天,然后在发布后立即找到了答案。

我编辑了代码以仅使用道具 defaultSource 并且现在可以按预期工作

    <Image
      source={{ uri: avatars[deferredKey] }}
      style={{
        width: size, height: size, borderRadius: size / 2, ...containerStyle,
      }}
      defaultSource={defaultAvatar}
    />
于 2020-05-20T16:40:49.690 回答