首页 文章

Mobx @computed函数带参数

提问于
浏览
2

我是Mobx的新手,但到目前为止它一直很好用,我已经成功了 . 我有一个反应本机应用程序与mobx和mobx-persist . 我正在使用axios从Wordpress网站上提取帖子 . 我正在努力改进的功能是“添加到收藏夹”功能 .

这是我的PostsStore:

export default class PostsStore {

// Define observables and persisting elements
@observable isLoading = true;
@persist('list') @observable posts = [];
@persist('list') @observable favorites = [];

// Get posts from Wordpress REST API
@action getPosts() {
  this.isLoading = true;
  axios({
    url: 'SITE_URL',
    method: 'get'
  })
    .then((response) => {
      this.posts = response.data
      this.isLoading = false
    })
    .catch(error => console.log(error))
}

// Add post to favorites list, ensuring that it does not previously exist
@action addToFavorites(id) {
  if (this.favorites.indexOf(id) === -1) {
    this.favorites.push(id);
  }
}

// Remove post from favorites list, ensuring that it does indeed exist
@action removeFromFavorites(id) {
  if (this.favorites.indexOf(id) !== -1) {
    this.favorites.remove(id);
  }
}

}

在我的收藏夹组件中,用于呈现添加或从收藏夹中删除的按钮,我认为使用@computed函数将首选确定正在呈现的当前帖子是否已添加到“id”可观察的'收藏'阵列 . 但是,似乎不允许@computed函数接受参数(如果它位于收藏夹可观察数组中,则最小参数将是post的'id'来评估 . 我可以使用@action完成测试但是没有'似乎立即更新渲染的屏幕,这是目标 . 正如下面的代码所示,我被迫在组件渲染中使用'if'语句执行测试 .

render () {
  if (this.props.postsStore.favorites.includes(this.props.item.id)) {
    return (
      <Button
        onPress={() => this.props.postsStore.removeFromFavorites(this.props.item.id)}
        title="★"
      />
    )
  }

这会影响我的应用程序的性能吗?是否有@computed方式来做我想要的?我不应该担心这个,因为它有点工作吗?

1 回答

  • 2

    这样做有效:

    @computed get isFavorite() {
       return createTransformer(id => this.favorites.includes(id))
    }
    

    在我的视图中调用如下:

    this.props.postsStore.isFavorite(this.props.item.id)
    

相关问题