You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native 实现用户认证后以表格形式展示API内容的开发咨询

React Native基础功能实现方案

1. 用户身份认证校验实现

  • 本地存储登录凭证:用户登录成功后,将后端返回的身份凭证(token)存入安全存储,可选用AsyncStorage或者针对Expo项目的expo-secure-store,避免明文存储敏感信息
  • 请求统一加鉴权字段:封装全局请求工具,所有API请求的请求头自动携带Authorization: Bearer ${token}字段,无需每次请求手动拼接
  • 无权限拦截:请求响应后统一校验状态码,若返回401无权限状态,直接清除本地存储的登录凭证,跳转至登录页面,避免无权限用户查看接口内容
  • 路由前置拦截:在路由跳转前校验本地是否存在有效token,未登录状态下直接拦截所有需要权限的页面访问,强制跳转登录页

核心代码示例

// 全局请求拦截器示例
import AsyncStorage from '@react-native-async-storage/async-storage';

const baseRequest = async (url, options = {}) => {
  // 自动注入token
  const token = await AsyncStorage.getItem('user_token');
  if (token) {
    options.headers = {
      ...options.headers,
      'Authorization': `Bearer ${token}`
    };
  }

  const response = await fetch(url, options);
  // 无权限直接拦截跳转
  if (response.status === 401) {
    await AsyncStorage.removeItem('user_token');
    // 此处替换为你的路由跳转逻辑
    navigation.replace('Login');
  }

  return response.json();
};

2. API内容表格展示实现

React Native官方没有内置表格组件,你可以选择直接封装轻量表格,或者引入第三方成熟表格组件实现:

  • 基础表格封装:基于View的flex布局,外层嵌套横向+纵向ScrollView适配长表格的滚动需求,表头单独设置背景色加粗和固定定位,提升可读性
  • 数据适配:拿到API返回的结构化数据后,先做格式转换,拆分为表头数组、行数据数组两类结构,直接传入表格组件渲染

轻量表格示例代码

import { ScrollView, View, Text, StyleSheet } from 'react-native';

const SimpleTable = ({ tableHeader, tableData }) => {
  return (
    <ScrollView horizontal showsHorizontalScrollIndicator={false}>
      <View>
        {/* 表头区域 */}
        <View style={styles.headerRow}>
          {tableHeader.map((headItem, index) => (
            <Text key={index} style={styles.headCell}>{headItem}</Text>
          ))}
        </View>
        {/* 表格内容区域 */}
        <ScrollView showsVerticalScrollIndicator={false}>
          {tableData.map((rowItem, rowIndex) => (
            <View key={rowIndex} style={styles.tableRow}>
              {rowItem.map((cellItem, cellIndex) => (
                <Text key={cellIndex} style={styles.tableCell}>{cellItem}</Text>
              ))}
            </View>
          ))}
        </ScrollView>
      </View>
    </ScrollView>
  )
}

const styles = StyleSheet.create({
  headerRow: {
    flexDirection: 'row',
    backgroundColor: '#f0f0f0'
  },
  headCell: {
    width: 120,
    paddingVertical: 12,
    paddingHorizontal: 8,
    fontWeight: '600'
  },
  tableRow: {
    flexDirection: 'row',
    borderBottomWidth: 1,
    borderBottomColor: '#eee'
  },
  tableCell: {
    width: 120,
    paddingVertical: 12,
    paddingHorizontal: 8
  }
})

export default SimpleTable;

内容的提问来源于stack exchange,提问作者Farukh Mohd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 03:30:05