React Native mobx绑定到FlatList不起作用

问题描述 投票:1回答:2

我有一个使用mobx的RN(0.44.2)FlatList(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 mobx-react react-native-flatlist
2个回答
3
投票

这是因为mobx的数组是对象,FlatList或react native中的数据需要一个数组。你可以在herethere上阅读更多相关信息。

Also...slice返回浅层副本;一个具有相同内容的新数组,而toJS也会转换数组中的值(但只有它们是可观察的)。


1
投票

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

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

Understanding what MobX reacts to

© www.soinside.com 2019 - 2024. All rights reserved.