如何在React Native中每次打开页面时刷新数据?

当前代码

App.js

const Mypage = {
  screen: MypageScreen,
  navigationOptions: () => ({
    headerShown: false,
  }),
};

const MypageStack = createStackNavigator(
  { Mypage },
  {
    initialRouteName: 'Mypage',
    navigationOptions: {
      title: 'Mypage',
    },
  },
);

const postLoginNavigator = createBottomTabNavigator({
  Mypage: MypageStack,
});

const AppNavigator = createStackNavigator({
  Loading,
  ...,
  PostLogin: postLoginNavigator,
}, {
  mode: 'modal',
  headerMode: 'none',
  initialRouteName: 'Loading',
});

const AppContainer = createAppContainer(AppNavigator);

export default class App extends React.Component {
  render() {
    return (
      <AppContainer />
    );
  }
}

Mypage.js

export default class Mypage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: '',
    };
  }

  async componentDidMount() {
    // getting how many items this user have
    const items = await db.getAllItems()
    // items is an array
    this.setState({
      items: items.length,
     });
  }

  render() {
    return (
      <View>
        <Text>Items</Text>
      </View>
      <View>
        <Text>
          { this.state.items }
        </Text>
      </View>
    );
  }
}

我要做什么

每次打开“我的页面”选项卡时,我都希望刷新数据。

mypage.js中的项目数正在更改,因此我想更新项目数。

或者,当仅项目数更改时,我想要更新的数字。

如果您能给我任何建议,我将不胜感激。

评论
女神
女神

For just checking number of items, you can always use items.length, but if you are looking for the case when your state should actually get updated data you can use shouldComponentUpdate

shouldComponentUpdate(nextProps, nextState){
  return nextState.items != this.state.items;
}
点赞
评论