zoukankan      html  css  js  c++  java
  • react-native中使用mobox数据共享

    安装依赖

    yarn add mobox

    yarn add mobox-react

    使用

    在组件A中引入mobox-react

    inject的作用是把公共的数据store注入到当前组件A中,在组件A中通过this.props.store可以获取公共数据

    observer的作用是监听store中的数据是否改变,一旦公共数据store改变了就去重新渲染组件

    import {inject ,observer} from 'mobox-react'

    import { inject, observer } from 'mobx-react'
    nterface Props {
        store?: any
    }
    interface State {
        selectedTab: string
    }
    
    @inject('store')
    @observer
    class Index extends Component<Props, State> {
      state = {
        selectedTab: 'cookbook'
      }
      //setState调用就会去触发@observer方法让组件重新渲染
      <View onPress={() => this.setState({ selectedTab: 'cookbook' })}></View>
        //使用本组件的state就是是this.state,使用store中的state就是this.props.state
        <TabNavigator.Item selected={this.state.selectedTab === 'menu'}></TabNavigator.Item>
        {
              this.props.store.isShow ?<View>调用的是公共store中的数据</View>:null
        }

     在公共数据存储store/index.js文件中

    import { observable, action, computed } from 'mobx'
    import { get } from '@/src/utils/http'
    
    class AppStore {
      @observable list = []
    
      @observable isShow = true
    
      @computed
      get swiper() {
    
      }
    
      @action
      setList(data) {
        this.list = data;
      }
    
      @action
      async getList() {
        let result = await get('http://192.168.2.1:8088/hotlist')
        this.setList(result)
      }
    
      @action
      setVisible(status) {
        this.isShow = status;
      }
    
    }
    
    export default new AppStore()

    在App.js中使用

    import store from '@/src/store/index'
    import { Provider } from 'mobx-react'
    export default function App() {
      return (
          <Provider store={store}>
           ...
          </Provider>
    
      );
    }
  • 相关阅读:
    AssetBundleNote
    UNet笔记
    HololensAR开发设置
    Hololens真机使用Unity开发流程
    数据结构笔记
    解决粘包问题
    使用C#中的Socket进行通讯
    解决Sql注入,防止恶意数据
    110. 平衡二叉树
    104.二叉树的最大深度
  • 原文地址:https://www.cnblogs.com/liuXiaoDi/p/12961655.html
Copyright © 2011-2022 走看看