React Native mobx 绑定到 FlatList 不起作用

React Native mobx binding to FlatList not working

我有一个使用 FlatList 的 RN (0.44.2) mobx (3.1.10) 应用程序。我基本上是在关注 https://blog.callstack.io/write-react-native-apps-in-2017-style-with-mobx-e2dffc209fcb

当使用我自己的商店时,与示例相反,我必须使用 toJS() 才能让 FlastList 呈现

    // renders list
    <FlatList
      data={this.props.giphyStore.images.toJS()}
      keyExtractor={(_, i) => i}
      renderItem={({ item }) => <Text>found the data</Text>}
    />

    // does not render list
    <FlatList
      data={this.props.giphyStore.images}
      keyExtractor={(_, i) => i}
      renderItem={({ item }) => <Text>did not find the data</Text>}
    />

我真的很难弄清楚为什么在某些情况下可能需要 toJS() 而在其他情况下不需要。

我的商店正在像这样设置图像可观察

async getImageList(query: string) {
  try {
    const requestURL = `${constants.GIPHY_ENDPOINT}${query}`
    const response = await axios.get(requestURL);
    const imgs = response.data.data.map((item) => {
      return { id: item.id, url: item.images.downsized.url }
    })
    this.images.replace(imgs)
  } catch (e) {
  }
}

作为后续问题,我不确定为什么我需要执行以下操作 this.images.replace(imgs),而在教程中他只是做了 this.tracks = response.data.tracks.items,这很好地触发了 observable。

如果有人有建议,我将不胜感激。

这是因为 mobx 的 数组是对象,FlatListreact native 中的数据需要一个数组。您可以在 here and there.

中阅读更多相关信息

Also..., slice returns浅拷贝;一个具有相同内容的新数组,而 toJS 也会转换数组内的值(但前提是它们是可观察的)。

这个问题有点老了,但也值得一提的是,MobX 默认只跟踪渲染函数,而 FlatList 接受渲染回调并调用它们。 (例如renderItem={this.renderItem}

为了在不刷新整个列表的情况下更新项目,用 <Observer> 包装渲染回调的结果。

Understanding reactivity [Mobx docs]