网络请求

React Native 教程 · 第 7 章 · 7 次浏览

RN 用 fetch(内置)或 axios 请求接口,JSON 数据渲染到界面。和 Web 写法几乎一样。

基本流程

  1. useEffect 里请求数据
  2. loading 状态显示加载动画
  3. 拿到数据 setState 渲染
  4. 错误处理显示提示

注意

安卓真机访问本机服务要用 10.0.2.2(模拟器)或局域网 IP;HTTP 明文要配 usesCleartextTraffic。

代码示例

import { useEffect, useState } from "react";
import { View, Text, FlatList, ActivityIndicator } from "react-native";

const App = () => {
  const [loading, setLoading] = useState(true);
  const [products, setProducts] = useState([]);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch("https://api.example.com/products")
      .then((res) => res.json())
      .then((data) => { setProducts(data); setLoading(false); })
      .catch((e) => { setError(String(e)); setLoading(false); });
  }, []);

  if (loading) return <ActivityIndicator size="large" style={{ marginTop: 50 }} />;
  if (error) return <Text style={{ padding: 20 }}>加载失败:{error}</Text>;

  return (
    <FlatList
      data={products}
      keyExtractor={(item) => String(item.id)}
      renderItem={({ item }) => <Text style={{ padding: 12 }}>{item.name} - ¥{item.price}</Text>}
    />
  );
};

export default App;
📚 JavaScript 语法速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
写法 / 语法作用
let x = 1;声明变量(可重新赋值)
const y = 2;声明常量(不可重新赋值)
var 已过时旧式变量声明,建议用 let/const
if (条件) { } else { }条件判断
for (let i = 0; i < n; i++) { }循环
while (条件) { }条件循环
function fn(a, b) { return a + b; }函数声明
const fn = (a) => a + 1;箭头函数
array.push(x) / pop()数组尾部添加 / 删除
array.map(fn) / filter(fn)数组映射 / 过滤
obj.key / obj["key"]访问对象属性
JSON.stringify(obj)对象转 JSON 字符串
JSON.parse(str)JSON 字符串转对象
document.getElementById("id")按 id 取元素
document.querySelector("选择器")按选择器取第一个元素
element.textContent读写元素文本
element.innerHTML读写元素 HTML(慎用,防 XSS)
element.addEventListener("click", fn)绑定事件
console.log(x)控制台输出(调试)
setTimeout(fn, 1000)延迟执行(毫秒)
window.location.href当前页面地址(可赋值跳转)
localStorage.setItem("k", v)本地存储写入
localStorage.getItem("k")本地存储读取
new Promise((resolve, reject) => {})Promise 异步处理
async / await异步函数语法糖