1

I have a RN (0.44.2) mobx (3.1.10) app which uses a FlatList. I'm basically following https://blog.callstack.io/write-react-native-apps-in-2017-style-with-mobx-e2dffc209fcb

When using my own store, opposed to the examples, I'm having to use toJS() in order to get the FlastList to render

    // 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>}
    />

I'm really struggling to figure out why toJS() might be needed in some cases and not others.

My store is setting the images observable like this

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) {
  }
}

As a follow up question, I'm not sure why I need to do the following this.images.replace(imgs) where as in the tutorial he simply did does this.tracks = response.data.tracks.items which triggers the observable just fine.

If anyone has suggestions, I would very much appreciate it.

4

2 回答 2

5

这是因为mobx 的数组是对象,而 react native 中的数据FlatList需要一个数组。你可以在这里那里阅读更多关于它的信息。

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

于 2017-08-13T19:38:13.740 回答
2

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

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

请参阅了解反应性 [Mobx 文档]

于 2017-12-18T15:47:39.787 回答