在app中集成Redux和React Navigation是一件很容易的事情,它基本和没有使用React Navigation时差不多。下面的例子展示了如何去使用它,并且最后给出了一个完整的例子https://snack.expo.io/@react-navigation/redux-example.其中最重要的代码片段就是下面这一段了
let RootStack = createStackNavigator({
Counter: CounterContainer,
StaticCounter: StaticCounterContainer,
});
let Navigation = createAppContainer(RootStack);
// Render the app container component with the provider around it
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<Navigation />
</Provider>
);
}
}
注意我们要将组件从createAppContainer中返回,并且用Provider将其包裹住。这样你就可以在你的App中随意使用connect方法了。
关于navigationOptions
好吧 这里的资料并不完整,我们假设你想要访问Redux stroe中的state,来更改其title。那么你要怎么做呢?这里有一堆options
假设我们想要计算数值然后用其更改title。
首先我们要使用connect方法
创建一个组件,将其用connect与store关联,然后赋值给组件中的title。
class Count extends React.Component {
render() {
return <Text>Count: {this.props.value}</Text>
}
}
let CountContainer = connect(state => ({ value: state.count }))(Count);
class Counter extends React.Component {
static navigationOptions = {
title: <CountContainer />
};
/* .. the rest of the code */
}
将state作为参数传递到页面中
如果你不想更改它的值,你可以仅仅将其作为参数从组件传递到页面中。
<Button
title="Go to static count screen"
onPress={() =>
this.props.navigation.navigate('StaticCounter', {
count: this.props.count,
})
}
/>
class StaticCounter extends React.Component {
static navigationOptions = ({ navigation }) => ({
title: navigation.getParam('count'),
});
render() {
return (
<View style={styles.container}>
<Text style={styles.paragraph}>
{this.props.navigation.getParam('count')}
</Text>
</View>
);
}
}
在你的screen中使用setParams方法
让我们来更改StaticCounter。
class StaticCounter extends React.Component {
static navigationOptions = ({ navigation }) => ({
title: navigation.getParam('count'),
});
componentDidMount() {
this.updateCount();
}
componentDidUpdate() {
this.updateCount();
}
updateCount() {
this.props.navigation.setParams({ count: this.props.count });
}
render() {
return (
<View style={styles.container}>
<Text style={styles.paragraph}>
{this.props.navigation.getParam('count')}
</Text>
</View>
);
}
}
现在无论store如何更新count的值,title都会跟着自动更新。