我正在使用createMaterialBottomTabNavigator
,它包含三个tabs
:
Tab3Component.js
class Tab3Component extends React.Component {
constructor(props) {
super(props);
this.props.navigation.setParams({
badgeCount: this.props.badgeCount,
})
}
static navigationOptions = ({ navigation }) => {
const { routeName } = navigation.state;
const badgeCount = navigation.getParam('badgeCount', null);
return {
tabBarIcon({ focused, horizontal, tintColor }) {
if (routeName === 'Tab3Component') {
return (
<View style={{ width: 24, height: 24, margin: 5}}>
<Image source={Icons.icon_tab3}
style={{
width: 24,
height: 24,
resizeMode: 'contain',
tintColor: tintColor
}} />
{
badgeCount != null && badgeCount > 0 &&
<Badge style={{
position: 'absolute',
bottom: '50%',
left: '50%',
}} size={20}>{badgeCount}</Badge>
}
</View>
);
}
}
};
}
componentDidUpdate(prevProps) {
if (prevProps.badgeCount != this.props.badgeCount) {
console.log(this.props.badgeCount)
this.props.navigation.setParams({
badgeCount: this.props.badgeCount, // Update the badgeCount once receive an update from the API.
})
}
}
}
const mapStateToProps = state => {
return {
// .. some stuffs here
badgeCount: state.badgeCount,
}
}
const mapDispatchToProps = dispatch => {
return {
//.. some stuffs here
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Tab3Component);
MainComponent.js
const MaterialTabNavigator = createMaterialBottomTabNavigator(
{
Tab1: { screen: Tab1Component },
Tab2: { screen: Tab2Component },
Tab3: { screen: Tab3Component },
},
{
initialRouteName: 'Tab1',
}
);
const TabNavigator = createAppContainer(MaterialTabNavigator);
class MainComponent extends React.Component {
//... some stuffs here
render() {
return(
//.. some stuffs here
<TabNavigator />
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(MainComponent);
当我单击badgeCount
时, Tab3
正在更新该值。但是我的问题是,一旦加载badgeCount
而不是仅仅单击MainComponent
,如何更新Tab3Component
的值?
感谢您的帮助,谢谢!
答案 0 :(得分:1)
请尝试以下。您可以使用redux钩子useSelector
从redux状态获取badgeCount
import { useSelector } from 'react-redux';
function BadgeIcon(props) {
// connect you badgeCount then render it here
const badgeCount = useSelector(state => state.badgeCount); // <-- get your badgeCount from redux state
return (
<View></View>
)
}
const MaterialTabNavigator = createMaterialBottomTabNavigator(
{
Tab1: { screen: Tab1Component },
Tab2: { screen: Tab2Component },
Tab3: {
screen: Tab3Component,
navigationOptions: () => ({
tabBarIcon: props => <BadgeIcon {...props} />,
}),
},
},
);