React Native:单击选项卡时重新渲染组件

时间:2018-04-24 11:35:48

标签: javascript reactjs react-native react-navigation

我正在使用React Navigation并尝试在单击选项卡时强制重新呈现组件(以及getData()函数)。

我试图关注this,但没有运气。

路由器

export const Tabs = TabNavigator(
  {
  Progress: {
    screen: ProgressStack,
    navigationOptions: ({ navigation }) => ({
      tabBarLabel: 'Progress',
      tabBarIcon: ({ tintColor }) =>
      <Icon name="trending-up" size={25} color={tintColor} />
    }),
  },
export const ProgressStack = StackNavigator({
  Progress: {
    screen: ProgressScreen,
    navigationOptions: ({ navigation }) => ({
      title: 'Progress',
    }),
  },
});

进度组件

componentWillReceiveProps() {
  console.log('rerender!');
  this.getData();
}

1 个答案:

答案 0 :(得分:2)

不是我尝试过的东西,但我认为这可能是正确的做法:https://reactnavigation.org/docs/with-navigation-focus.html

使用该高阶组件传递isFocusedProp,然后使用componentDidUpdate来调用getData

componentDidUpdate (previousProps) {
  if (!previousProps.isFocused && this.props.isFocused) {
    this.getData()
  }
}

还有一个可以使用的onPress按钮事件:https://reactnavigation.org/docs/tab-navigator.html#tabbaronpress,但这需要一种方法来触发您正在进行的数据通话。如果您正在使用redux,则需要通过路径参数传递dispatch或绑定的动作函数。