我是 Mobx 的新手,但到目前为止,它运行良好,并且我已经取得了很大的进展。我有一个带有 mobx 的反应本机应用程序,并且 mobx-persist 。我正在使用 axios 从 Wordpress 网站提取帖子。我试图改进的功能是“添加到收藏夹”功能。
这是我的 PostStore:
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);
}
}
}
在我的收藏夹组件中,该组件旨在呈现一个用于添加或从收藏夹中删除的按钮,我认为最好使用 @compulated 函数来确定当前呈现的帖子是否具有已添加到的“id”可观察的“收藏夹”数组。然而,似乎 @compulated 函数不允许接受参数(最小参数是帖子的“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="★"
/>
)
}
这会影响我的应用程序的性能吗?有没有@compated 的方法来做我想做的事?既然它有点起作用,我应该不担心这个吗?
这样做有效:
@computed get isFavorite() {
return createTransformer(id => this.favorites.includes(id))
}
在我看来,这样称呼:
this.props.postsStore.isFavorite(this.props.item.id)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)