热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

使用MobX开发ReactNative应用@observer引用报错

本文将MobX与ReactNative结合,编写一个简单的列表客户端。这是学习使用MobX和ReactNative的一个不错的起点。查看最终的代码库,点





本文将 MobX 与 React Native 结合,编写一个简单的列表客户端。这是学习使用 MobX 和 React Native 的一个不错的起点。

使用 MobX 开发 React Native 应用

使用 MobX 开发 React Native 应用

查看最终的代码库,点击这里。

MobX 是一款精准的状态管理工具库,对我来说非常容易学习和接受。我在 React 和 React Native 应用中使用过 Flux、Alt、Redux 和 Reflux,但我会毫不犹豫地说,MobX 的简单性立即成为了我最喜欢的状态管理工具。我期望能将它运用在未来的项目中,并且对 MobX 的发展拭目以待。

我们要开发的客户端有两个主要的组件,一个是创建新的列表,一个是向列表中加入新的条目。

使用 MobX 开发 React Native 应用

首先,我们先要创建一个 React Native 应用:

react-native init ReactNativeMobX

接下来,我们进入目录下,并安装需要的依赖:mobxmobx-react

npm i mobx mobx-react --save

我们也要安装一些 babel 插件,以支持 ES7 的 decorator 特性:

npm i babel-plugin-transform-decorators-legacy babel-preset-react-native-stage-0 --save-dev

现在,创建一个 .babelrc 文件配置 babel 插件:

{'presets': ['react-native'],'plugins': ['transform-decorators-legacy']
}

因为我们编写的是一个自定义 .babelrc 文件,所有只需要 react-native 的 preset。配置 react-native 的 preset,还有指定一些先期运行的插件(我们这里是 transform-decorators-legacy 插件)。

现在,我们的项目配置好了,开始写代码。

在根目录,创建一个叫做 app 的目录。在 app 里面创建一个叫做 mobx 的目录,在 mobx 里创建一个叫做 listStore.js 的文件:

import {observable} from 'mobx'

let index = 0

class ObservableListStore {
@observable list = []

addListItem (item) {
this.list.push({
name: item,
items: [],
index
})
index++
}

removeListItem (item) {
this.list = this.list.filter((l) => {
return l.index !== item.index
})
}

addItem(item, name) {
this.list.forEach((l) => {
if (l.index === item.index) {
l.items.push(name)
}
})
}
}

const observableListStore = new ObservableListStore()
export default observableListStore


  1. mobx 导入 observableobservable 可以给存在的数据结构如对象、数组和类增加可观察的能力。简单地给类属性增加一个 @observable 装饰器(下一代 ECMAScript),或者调用 observable 或 extendObservable 函数(ES5);
  2. 创建一个叫做 ObservableListStore 的类;
  3. 创建一个可观察的数组 list;
  4. 创建三个操作列表数组的方法;
  5. 创建一个 ObservableListStore 的实例 observableListStore;
  6. 导出 observableListStore

现在已经用了存储器,我们修改项目的入口文件,使用存储,创建导航。如果你开发是 Android 项目,入口文件是 index.Android.js,如果是 iOS 项目,则是 index.iOS.js

import React, { Component } from 'react'
import App from './app/App'
import ListStore from './app/mobx/listStore'

import {
AppRegistry,
Navigator
} from ‘react-native’

class ReactNativeMobX extends Component {
renderScene (route, navigator) {
return
}
configureScene (route, routeStack) {
if (route.type === ‘Modal’) {
return Navigator.SceneConfigs.FloatFromBottom
}
return Navigator.SceneConfigs.PushFromRight
}
render () {
return (
configureScene={this.configureScene.bind(this)}
renderScene={this.renderScene.bind(this)}
initialRoute={{
component: App,
passProps: {
store: ListStore
}
}} />
)
}
}

AppRegistry.registerComponent(‘ReactNativeMobX’, () => ReactNativeMobX)

在入口文件中我们创建了一个基本的导航状态,并导入了新创建的数组存储器。在 initialRoute 中我们传入数据存储作为属性。我们还把已经创建的组件 App 作为初始路由。App 将会访问属性中的数据存储。

在 configureScene 中,我们检查类型(type)是否是 ‘Modal’,是则返回 floatFromBottom 这个场景配置项,可以把下一个场景也设置为模态的。

现在,我们来创建应用组件。这确是一个大型的组件,还有很多需要完善的地方,但我们创建了一个允许增加和删除列表条目的基本用户界面。调用数据存储的方法来和我们的应用状态交互。app/App.js 的内容:

import React, { Component } from 'react'
import { View, Text, TextInput, TouchableHighlight, StyleSheet } from 'react-native'
import {observer} from 'mobx-react/native'
import NewItem from './NewItem'

@observer
class TodoList extends Component {
constructor () {
super()
this.state = {
text: ‘’,
showInput: false
}
}
toggleInput () {
this.setState({ showInput: !this.state.showInput })
}
addListItem () {
this.props.store.addListItem(this.state.text)
this.setState({
text: ‘’,
showInput: !this.state.showInput
})
}
removeListItem (item) {
this.props.store.removeListItem(item)
}
updateText (text) {
this.setState({text})
}
addItemToList (item) {
this.props.navigator.push({
component: NewItem,
type: ‘Modal’,
passProps: {
item,
store: this.props.store
}
})
}
render() {
const { showInput } = this.state
const { list } = this.props.store
return (


My List App

{!list.length ? : null}

{list.map((l, i) => {
return
style={styles.item}
onPress={this.addItemToList.bind(this, l)}>{l.name.toUpperCase()}
style={styles.deleteItem}
onPress={this.removeListItem.bind(this, l)}>Remove

})}

underlayColor=‘transparent’
onPress={
this.state.text === ‘’ ? this.toggleInput.bind(this)
: this.addListItem.bind(this, this.state.text)
}
style={styles.button}>

{this.state.text === ‘’ && ‘+ New List’}
{this.state.text !== ‘’ && ‘+ Add New List Item’}


{showInput && style={styles.input}
onChangeText={(text) => this.updateText(text)} />}

);
}
}

const NoList = () => (

No List, Add List To Get Started

)

const styles = StyleSheet.create({
itemContainer: {
borderBottomWidth: 1,
borderBottomColor: ‘#ededed’,
flexDirection: ‘row’
},
item: {
color: ‘#156e9a’,
fontSize: 18,
flex: 3,
padding: 20
},
deleteItem: {
flex: 1,
padding: 20,
color: ‘#a3a3a3’,
fontWeight: ‘bold’,
marginTop: 3
},
button: {
height: 70,
justifyContent: ‘center’,
alignItems: ‘center’,
borderTopWidth: 1,
borderTopColor: ‘#156e9a’
},
buttonText: {
color: ‘#156e9a’,
fontWeight: ‘bold’
},
heading: {
height: 80,
justifyContent: ‘center’,
alignItems: ‘center’,
borderBottomWidth: 1,
borderBottomColor: ‘#156e9a’
},
headingText: {
color: ‘#156e9a’,
fontWeight: ‘bold’
},
input: {
height: 70,
backgroundColor: ‘#f2f2f2’,
padding: 20,
color: ‘#156e9a’
},
noList: {
flex: 1,
justifyContent: ‘center’,
alignItems: ‘center’
},
noListText: {
fontSize: 22,
color: ‘#156e9a’
},
})

export default TodoList

我来解释此文件中可能不明确的地方。如果你有什么还不明白的,请留言,我会更新和回复。


  1. mobx-react/native 导入 observer;
  2. 使用 @observer 装饰器描述类,确保相关数组变化后组件独立地重渲染;
  3. 导入已经创建好的组件 NewItem。这是我们要增加新条目时转向的组件;
  4. addListItem中,把 this.state.text 传入 this.props.store.addListItem。在与输入框绑定的 updateText 中会更新 this.state.text;
  5. removeListItem 中调用 this.props.store.removeListItem 并传入条目;
  6. addItemToList 中调用 this.props.navigator.push,传入条目和数组存储两个参数;
  7. 在 render 方法中,通过属性解构数据存储:

    const { list } = this.props.store

  8. 在 render 方法中,也创建了界面,并绑定了类的方法

最后,创建 NewItem 组件:

import React, { Component } from 'react'
import { View, Text, StyleSheet, TextInput, TouchableHighlight } from 'react-native'

class NewItem extends Component {
constructor (props) {
super(props)
this.state = {
newItem: ‘’
}
}
addItem () {
if (this.state.newItem === ‘’) return
this.props.store.addItem(this.props.item, this.state.newItem)
this.setState({
newItem: ‘’
})
}
updateNewItem (text) {
this.setState({
newItem: text
})
}
render () {
const { item } = this.props
return (


{item.name}
onPress={this.props.navigator.pop}
style={styles.closeButton}>×

{!item.items.length && }
{item.items.length ? : }

value={this.state.newItem}
onChangeText={(text) => this.updateNewItem(text)}
style={styles.input} />
onPress={this.addItem.bind(this)}
style={styles.button}>
Add



)
}
}

const NoItems = () => (

No Items, Add Items To Get Started

)
const Items = ({items}) => (

{items.map((item, i) => {
return • {item}
})
}

)

const styles = StyleSheet.create({
heading: {
height: 80,
justifyContent: ‘center’,
alignItems: ‘center’,
borderBottomWidth: 1,
borderBottomColor: ‘#156e9a’
},
headingText: {
color: ‘#156e9a’,
fontWeight: ‘bold’
},
input: {
height: 70,
backgroundColor: ‘#ededed’,
padding: 20,
flex: 1
},
button: {
width: 70,
height: 70,
justifyContent: ‘center’,
alignItems: ‘center’,
borderTopWidth: 1,
borderColor: ‘#ededed’
},
closeButton: {
position: ‘absolute’,
right: 17,
top: 18,
fontSize: 36
},
noItem: {
flex: 1,
justifyContent: ‘center’,
alignItems: ‘center’
},
noItemText: {
fontSize: 22,
color: ‘#156e9a’
},
item: {
color: ‘#156e9a’,
padding: 10,
fontSize: 20,
paddingLeft: 20
}
})

export default NewItem

如果你对 React 或 React Native 熟悉,上面就没什么特别的。基本上就是访问条目的属性,遍历条目的数组,判断是否以及存在。存在则显示一条消息。

组件中我们与数据存储的唯一一处位置就是 addItem,向 this.props.store.addItem 传入了 this.props.item 和 this.state.newItem

就这么多!

查看最终的代码库,点击这里。


推荐阅读
  • 本文详细记录了在银河麒麟操作系统和龙芯架构上使用 Qt 5.15.2 进行项目打包时遇到的问题及解决方案,特别关注于 linuxdeployqt 工具的应用。 ... [详细]
  • 本文详细介绍如何使用Samba软件配置CIFS文件共享服务,涵盖安装、配置、权限管理及多用户挂载等关键步骤。通过具体示例和命令行操作,帮助读者快速搭建并优化Samba服务器。 ... [详细]
  • CentOS系统安装与配置常见问题及解决方案
    本文详细介绍了在CentOS系统安装过程中遇到的常见问题及其解决方案,包括Vi编辑器的操作、图形界面的安装、网络连接故障排除等。通过本文,读者可以更好地理解和解决这些常见问题。 ... [详细]
  • CentOS7源码编译安装MySQL5.6
    2019独角兽企业重金招聘Python工程师标准一、先在cmake官网下个最新的cmake源码包cmake官网:https:www.cmake.org如此时最新 ... [详细]
  • UNP 第9章:主机名与地址转换
    本章探讨了用于在主机名和数值地址之间进行转换的函数,如gethostbyname和gethostbyaddr。此外,还介绍了getservbyname和getservbyport函数,用于在服务器名和端口号之间进行转换。 ... [详细]
  • 作为一名新手,您可能会在初次尝试使用Eclipse进行Struts开发时遇到一些挑战。本文将为您提供详细的指导和解决方案,帮助您克服常见的配置和操作难题。 ... [详细]
  • MySQL 数据库迁移指南:从本地到远程及磁盘间迁移
    本文详细介绍了如何在不同场景下进行 MySQL 数据库的迁移,包括从一个硬盘迁移到另一个硬盘、从一台计算机迁移到另一台计算机,以及解决迁移过程中可能遇到的问题。 ... [详细]
  • 根据最新发布的《互联网人才趋势报告》,尽管大量IT从业者已转向Python开发,但随着人工智能和大数据领域的迅猛发展,仍存在巨大的人才缺口。本文将详细介绍如何使用Python编写一个简单的爬虫程序,并提供完整的代码示例。 ... [详细]
  • 本文介绍了一种在 MySQL 客户端执行 NOW() 函数时出现时间偏差的问题,并详细描述了如何通过配置文件调整时区设置来解决该问题。演示场景中,假设当前北京时间为2023年2月17日19:31:37,而查询结果显示的时间比实际时间晚8小时。 ... [详细]
  • JavaScript 基础语法指南
    本文详细介绍了 JavaScript 的基础语法,包括变量、数据类型、运算符、语句和函数等内容,旨在为初学者提供全面的入门指导。 ... [详细]
  • 基于Node.js、Express、MongoDB和Socket.io的实时聊天应用开发
    本文详细介绍了使用Node.js、Express、MongoDB和Socket.io构建的实时聊天应用程序。涵盖项目结构、技术栈选择及关键依赖项的配置。 ... [详细]
  • ElasticSearch 集群监控与优化
    本文详细介绍了如何有效地监控 ElasticSearch 集群,涵盖了关键性能指标、集群健康状况、统计信息以及内存和垃圾回收的监控方法。 ... [详细]
  • 在寻找轻量级Ruby Web框架的过程中,您可能会遇到Sinatra和Ramaze。两者都以简洁、轻便著称,但它们之间存在一些关键区别。本文将探讨这些差异,并提供详细的分析,帮助您做出最佳选择。 ... [详细]
  • PyCharm下载与安装指南
    本文详细介绍如何从官方渠道下载并安装PyCharm集成开发环境(IDE),涵盖Windows、macOS和Linux系统,同时提供详细的安装步骤及配置建议。 ... [详细]
  • 本文详细介绍如何使用Python进行配置文件的读写操作,涵盖常见的配置文件格式(如INI、JSON、TOML和YAML),并提供具体的代码示例。 ... [详细]
author-avatar
u44093631
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有