首页 > 解决方案 > React Native:单击选项卡时重新渲染组件

问题描述

我正在使用 React Navigation 并试图getData()在单击选项卡时强制重新渲染组件(和函数)。

我试图遵循这一点,但没有运气。

路由器

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();
}

标签: javascriptreactjsreact-nativereact-navigation

解决方案


我没有尝试过,但我认为这可能是正确的方法: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,则需要通过路由参数传递调度或绑定的操作函数。


推荐阅读