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>
    
      );
    }
  • 相关阅读:
    Codeforces Beta Round #9 (Div. 2 Only) C. Hexadecimal's Numbers dfs
    Codeforces Beta Round #9 (Div. 2 Only) B. Running Student 水题
    Codeforces Beta Round #9 (Div. 2 Only) A. Die Roll 水题
    51nod 1035 最长的循环节 数学
    BSGS 模板
    51nod 1040 最大公约数之和 欧拉函数
    51NOD 1179 最大的最大公约数 筛法
    BZOJ 2818: Gcd 筛法
    川大校赛总结
    SCOJ 4484 The Graver Robbers' Chronicles 后缀自动机
  • 原文地址:https://www.cnblogs.com/liuXiaoDi/p/12961655.html
Copyright © 2011-2022 走看看