react-native中使用mobox数据共享
生活随笔
收集整理的這篇文章主要介紹了
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>
);
}
總結
以上是生活随笔為你收集整理的react-native中使用mobox数据共享的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 预售80万起 新款日产全尺寸SUV途乐今
- 下一篇: Android 开发 VectorDr