reactjs - 使用状态更新 navigationOptions 中的 tabBarIcon,不起作用
问题描述
我正在尝试在 React Native 中动态更改来自 navigationOptions 的 tabNavigator 的徽章。
我正在尝试使用 setState 更改它,但它没有更新。
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
postsBadgeCount: 0,
progressBadgeCount: 0
};
this.Apps = this.startApp();
}
componentDidMount() {
setInterval(() => {
this.setState({ progressBadgeCount: this.state.progressBadgeCount + 1 });
console.log('change state', this.state.progressBadgeCount);
}, 5000);
}
startApp() {
const BottomNav = createMaterialBottomTabNavigator({
Progress: {
screen: stack2,
navigationOptions: {
tabBarLabel: 'Progress',
tabBarIcon: ({ tintColor }) => (
<View>
<IconFA name="calendar-check-o" size={22} color={tintColor} />
{this.state.progressBadgeCount > 0 ?
<View style={style.badge}>
<Text style={style.badgeCount}>1</Text>
</View> : undefined}
</View>
)
}
},
{
...
});
const navigator = createSwitchNavigator(
...
);
return createAppContainer(navigator);
}
render() {
return (
<this.Apps/>
);
}
}
当我尝试使用 setState 更新 progressBadgeCount 时,它不会在 UI 上更改。
在这种情况下如何更新徽章计数有什么建议吗?谢谢
解决方案
startApp()
在构造函数中只运行一次。您可以将其this.Apps
更改render()
为:
render() {
return this.startApp();
}
这样它会startApp()
在每次重新渲染时运行。