我正在使用react-navigation,这是我的结构:
根堆栈导航器:
export const Root = StackNavigator({
Index: {
screen: Index,
navigationOptions: ({ navigation }) => ({
}),
},
Cart: {
screen: Cart,
navigationOptions: ({ navigation }) => ({
title: 'Votre panier',
drawerLabel: 'Cart',
drawerIcon: ({ tintColor }) => <Icon theme={{ iconFamily: 'FontAwesome' }} size={26} name="shopping-basket" color={tintColor} />
}),
},
...我的结构是这样的:
所以我的问题是,在哪里加载数据,初始化我的应用程序?我需要一个叫我一次的地方,在其他页面之前打电话给我。
我的应用程序中显示的第一个页面是MyPage页面。但是正如你所看到的,由于TabNavigator,如果我把我的函数放在里面,它将被多次调用。
有些人会在闪存屏幕上说,但是我使用的是主溅屏元件,我对它没有太多的控制。
我想到了我们创建提供者的App.js,但我不认为这是个好主意?
const MyApp = () => {
//TODO We're loading the data here, I don't know if it's the good decision
ApplicationManager.loadData(store);
SplashScreen.hide();
return (
<Provider store={store}>
<Root/>
</Provider>
);
};做这个的好方法是什么?
发布于 2017-11-06 23:36:26
class MyApp extends Component {
state = {
initialized: false
}
componentWillMount() {
// if this is a promise, otherwise pass a callback to call when it's done
ApplicationManager.loadData(store).then(() => {
this.setState({ initialized: true })
})
}
render() {
const { initialized } = this.state
if (!initialized) {
return <SplashScreen />
}
return (
<Provider store={store} >
<Root />
</Provider>
);
}
}发布于 2017-11-07 20:59:47
默认情况下,TabNavigator同时呈现/加载其所有子组件,但如果设置属性,则只有在导航时lazy: true组件才会呈现。这意味着你的函数不会被多次调用。
const Tabs = TabNavigator(
{
MyPage : {
screen: MyPage
},
MyPage2 : {
screen: MyPage,
}
}
},
{
lazy: true
}
);如果在MyPage中使用此结构并调用获取数据,则可以在componentWillReceiveProps中添加逻辑,以检查已存储的数据和/或在获取新数据之前是否对其进行更改。从MyPage调用获取函数可以在每次页面/屏幕访问中提取新数据,或者在需要时执行“拉刷新”操作。
你也可以在闪屏时间提取初始数据,我只是不建议你的所有应用程序数据,所有屏幕的数据,当时,因为你可能不需要它在一次。你可以这样做:
class MyApp extends Component {
state = {
initialized: false
}
componentWillMount() {
// if this is a promise, otherwise pass a callback to call when it's done
ApplicationManager.loadData(store).then(() => {
this.setState({ initialized: true })
})
}
render() {
const { initialized } = this.state
if (!initialized) {
return null
}
return (
<Provider store={store} >
<Root />
</Provider>
);
}
}
class Root extends Component {
componentDidMount() {
SplashScreen.hide();
}
...
}发布于 2017-11-05 19:53:56
您应该在App.js或初始化StackNavigator的地方这样做。如果我是您,我会放置一个加载屏幕,一旦数据准备就绪,它将被StackNavigator结构所取代。
https://stackoverflow.com/questions/47070585
复制相似问题