#mobx应用在rn项目中

 

第一步先建立一个类似redux中reducer的文件
runInAction可以解决获取异步数据问题
import { observable, action, runInAction } from 'mobx'

class List {
  // 树叶变成响应数据
  @observable listData: Array<any> = []

  // @computed计算属性
  // MobX 配置为需要通过动作来更改状态时,必须使用 action,做一些事件
  @action
  getCateData () {
    fetch('https://ik9hkddr.qcloud.la/mock/cookbook-list.json')
      .then(reponse => reponse.json())
      .then(result => {
        runInAction(() => {
          this.listData = result.data
        })
      })
  }
}

export default new List()
第二步在 利用mobx-react将mobx和react粘合,并在componentDidMount钩子中触发获取数据的函数action
import React from 'react'
import { Provider } from 'mobx-react'

import Home from './pages/home/Home'
import store from './store'

export default class componentName extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <Home></Home>
      </Provider>
    )
  }

  componentDidMount () {
    store.list.getCateData()
  }
}
第三步将store注入要用数据的组件
import { observer, inject } from 'mobx-react'
interface Props {
  store?: any
}

interface State {
  hotCateList: Array<any>
  list: Array<any>
}
//inject将store注入组件
@inject('store')
// @observer吧数据变成响应式
@observer
export default class componentName extends Component<Props, State> {
}

第四步 直接在树枝上获取数据,在render中渲染
render() {
    const listData = this.props.store.list.listData
    return ()}

 

 

    

 

转载于:https://www.cnblogs.com/w-819/p/10047390.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值