🎯 技术专家导语
你的 App 不可能只靠本地运行,想要获取用户信息、发送验证码、加载商品数据……就必须与“外部世界”进行网络通信。
React Native 支持使用 fetch、axios 等主流方案,既保留 Web 习惯,又兼容原生能力。
🌐 一、使用 fetch 请求数据(内置方案)
🔰 基本写法
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('出错啦:', error))
- ✅ API 简单,无需额外依赖
- ⚠️ 不支持请求超时控制、不自动携带 Cookie
📦 二、使用 axios 更强大
🔧 安装 axios
npm install axios
🚀 使用示例
import axios from 'axios'
axios.get('https://api.example.com/user', {
headers: {
Authorization: `Bearer ${token}`
}
})
.then(res => console.log(res.data))
.catch(err => console.error(err))
🎯 高级用法
const instance = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000,
headers: { 'X-Custom-Header': 'foobar' }
})
🔐 三、常见场景封装
✅ 封装统一请求方法
export const request = async (url, params = {}, method = 'GET') => {
try {
const res = await axios({
url,
method,
data: method === 'POST' ? params : undefined,
params: method === 'GET' ? params : undefined
})
return res.data
} catch (err) {
console.warn('请求失败:', err)
throw err
}
}
🧠 四、Tips & 常见问题
| 问题 | 原因与解决方案 |
|---|---|
| 网络请求失败 | 模拟器未联网 / 地址拼错 / 后端跨域 |
| Android 无法请求本地接口 | 使用 10.0.2.2 替代 localhost |
| 响应太慢 | 设置 axios.timeout 或使用节流逻辑 |
| 权限问题(如上传图片) | 需申请 READ/WRITE_EXTERNAL_STORAGE 权限 |
🧩 五、结合 UI 显示状态
const [loading, setLoading] = useState(false)
const [data, setData] = useState(null)
const loadData = async () => {
setLoading(true)
const res = await request('/product/list')
setData(res)
setLoading(false)
}
✅ 总结
- ✅
fetch适合简单请求,axios推荐用于生产项目 - ✅ 抽离请求逻辑,提升复用性
- ✅ 配合状态管理展示加载中、错误提示
📘 下一篇预告:
👉 《适配 + 性能优化:做个“跑得快、看得清”的 App》