Joh*_*son 6 react-native mobx mobx-react
我是 Mobx 的新手,但到目前为止它运行良好,而且我已经取得了很大进展。我有一个带有 mobx 和 mobx-persist 的 react-native 应用程序。我正在使用 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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我的收藏夹组件中,该组件旨在呈现一个按钮以添加或从收藏夹中删除,我认为最好使用 @computed 函数来确定正在呈现的当前帖子是否具有已添加到的“id”可观察的“收藏夹”数组。但是,似乎不允许@computed 函数接受参数(最小参数将是帖子的“id”,以评估它是否在收藏夹可观察数组中。我可以使用@action 完成测试,但不会“ t似乎立即更新渲染的屏幕,这是目标。正如下面的代码所示,我被迫在组件渲染中使用“if”语句执行测试。
render () {
if (this.props.postsStore.favorites.includes(this.props.item.id)) {
return (
<Button
onPress={() => this.props.postsStore.removeFromFavorites(this.props.item.id)}
title="?"
/>
)
}
Run Code Online (Sandbox Code Playgroud)
这会影响我的应用程序的性能吗?有没有@computed 方法来做我想做的事?我应该不担心这个,因为它有点工作?
这样做有效:
@computed get isFavorite() {
return createTransformer(id => this.favorites.includes(id))
}
Run Code Online (Sandbox Code Playgroud)
在我看来是这样调用的:
this.props.postsStore.isFavorite(this.props.item.id)
Run Code Online (Sandbox Code Playgroud)
只是为了完整性:mobx-utils现在提供了一种在计算函数中使用参数的方法。您可以使用computedFn并声明您的函数,如下所示:
isFavorite = computedFn(function isFavorite(id) {
return this.favorites.includes(id)
})
Run Code Online (Sandbox Code Playgroud)
查看文档中的文章。
| 归档时间: |
|
| 查看次数: |
6068 次 |
| 最近记录: |