如何基于react-native中useSelector挂钩的值来操作视图

时间:2019-11-12 08:16:52

标签: react-native react-redux

我正在根据我从auth redux存储中获得的角色来显示菜单。我正在使用useSelector()钩子来从redux获取角色。

当我尝试添加条件并根据其所包含的角色返回不同的视图时。下面是我的代码示例。

import HeaderButton from '../components/HeaderButton';
import React, { useState, useEffect, useCallback } from 'react';
import {
  View,
  Text,
  FlatList,
  Button,
  Platform,
  ActivityIndicator,
  StyleSheet,
  AsyncStorage,
} from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import { HeaderButtons, Item } from 'react-navigation-header-buttons';

import * as siteActions from '../store/actions/sites';
import Colors from '../constants/Colors';
import MenuItem from '../components/MenuItem';

const LandingScreen = props => {
  const roles = useSelector(state => state.auth.roles);
  console.log(roles); //Here I am getting roles as (Admin,User,Approver)
  const selectMenuNavigation = page => {
    if (page === 'Upload') {
      props.navigation.navigate('SelectSite', {
        nextNav: page,
      });
    }
    if (page === 'View') {
      props.navigation.navigate('SelectSite', {
        nextNav: page,
      });
    }
  };

  if (roles.indexOf('Admin') != -1) {
    //roles becomes undefined once I write this line
    return (
      <View>
        <MenuItem
          title="Upload Images"
          onSelect={() => {
            selectMenuNavigation('Upload');
          }}
        />
        <MenuItem
          title="View Images"
          onSelect={() => {
            selectMenuNavigation('View');
          }}
        />
        <MenuItem
          title="Update Sites"
          onSelect={() => {
            selectMenuNavigation('Sites');
          }}
        />
        <MenuItem
          title="Update Users"
          onSelect={() => {
            selectMenuNavigation('Users');
          }}
        />
      </View>
    );
  }

  if (roles.indexOf('User') != -1) {
    return (
      <View>
        <MenuItem
          title="Upload Images"
          onSelect={() => {
            selectMenuNavigation('Upload');
          }}
        />
      </View>
    );
  }

  if (roles.indexOf('Approver') != -1) {
    return (
      <View>
        <MenuItem
          title="Upload Images"
          onSelect={() => {
            selectMenuNavigation('Upload');
          }}
        />
        <MenuItem
          title="View Images"
          onSelect={() => {
            selectMenuNavigation('View');
          }}
        />
      </View>
    );
  }
};

export default LandingScreen;

一旦写入if条件,roles变量的值将变为undefined。如果从钩子实现的角度看有什么问题,可以帮我吗?

0 个答案:

没有答案