React Native页面间传参及数据持久化实现方案咨询
解决方案:React Native预约数据持久化问题
你遇到的核心问题是route.params仅能在页面跳转时临时传递数据,一旦页面重载、APP重启或从后台恢复,参数就会丢失。结合你的现有代码(已经对接后端API),推荐以下几种可靠的解决方案:
方案一:直接从后端API拉取所有预约数据(最推荐)
既然你的预约页面已经通过fetchAgendamentos从API获取数据,那My Appointments页面完全可以复用这个逻辑,直接从后端拉取当前用户的所有预约,不需要依赖跳转时的参数。这样数据始终和后端保持同步,天然持久化。
实现步骤:
- 在My Appointments页面中,复制或复用
fetchAgendamentos函数(建议抽成公共工具函数,避免重复代码) - 页面加载时调用该函数,获取并渲染所有预约数据
My Appointments页面示例代码:
import React, { useState, useEffect } from 'react'; import { View, Text, FlatList, StyleSheet } from 'react-native'; const MeusAgendamentos = () => { const [agendamentos, setAgendamentos] = useState([]); useEffect(() => { fetchAgendamentos(); }, []); const fetchAgendamentos = async () => { try { const response = await fetch(API_URL); // 替换为你的实际API地址 const data = await response.json(); // 如果需要过滤当前用户的预约,在这里添加逻辑,比如 data.filter(item => item.userId === 当前用户ID) setAgendamentos(data); } catch (error) { console.error("Erro ao buscar agendamentos:", error); } }; const renderItem = ({ item }) => ( <View style={styles.card}> <Text style={styles.nome}>{item.nome} - {item.prof}</Text> <Text style={styles.data}>Data: {item.data}</Text> <Text style={styles.obs}>Observação: {item.obs}</Text> </View> ); return ( <FlatList data={agendamentos} renderItem={renderItem} keyExtractor={(item) => item.id.toString()} /> ); }; const styles = StyleSheet.create({ card: { padding: 16, margin: 8, backgroundColor: '#fff', borderRadius: 8, shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.1, shadowRadius: 4, elevation: 3, }, nome: { fontSize: 16, fontWeight: 'bold', marginBottom: 4, }, data: { fontSize: 14, color: '#666', marginBottom: 2, }, obs: { fontSize: 14, color: '#888', }, }); export default MeusAgendamentos;
方案二:使用全局状态管理(Context API)
如果你的APP需要在多个页面共享预约数据,或者不想每次都调用API,可以用React的Context API把数据存在全局状态中,两个页面都从全局状态读取数据。
实现步骤:
- 创建全局Context,用于存储预约数据和更新方法
- 在App组件或父组件中提供Context的值
- 在预约页面和My Appointments页面中订阅Context
示例代码:
1. 创建Context文件(AgendamentoContext.js)
import React, { createContext, useState, useEffect } from 'react'; export const AgendamentoContext = createContext(); export const AgendamentoProvider = ({ children }) => { const [agendamentos, setAgendamentos] = useState([]); useEffect(() => { fetchAgendamentos(); }, []); const fetchAgendamentos = async () => { try { const response = await fetch(API_URL); const data = await response.json(); setAgendamentos(data); } catch (error) { console.error("Erro ao buscar agendamentos:", error); } }; // 提供更新数据的方法,新增/删除后同步全局状态 const updateAgendamentos = (newData) => { setAgendamentos(newData); }; return ( <AgendamentoContext.Provider value={{ agendamentos, updateAgendamentos, fetchAgendamentos }}> {children} </AgendamentoContext.Provider> ); };
2. 在App.js中包裹Provider
import { AgendamentoProvider } from './AgendamentoContext'; export default function App() { return ( <AgendamentoProvider> {/* 你的导航组件或其他页面 */} </AgendamentoProvider> ); }
3. 在预约页面中使用Context
修改salvarAgendamento和handleDelete函数,更新全局状态:
import { useContext } from 'react'; import { AgendamentoContext } from './AgendamentoContext'; const AgendamentoAdv = () => { const { updateAgendamentos, fetchAgendamentos } = useContext(AgendamentoContext); // ... 其他原有代码 const salvarAgendamento = async () => { // ... 原有代码 fetchAgendamentos(); // 调用全局的fetch方法更新状态 fecharModal(); }; const handleDelete = async (id) => { try { const response = await fetch(`${API_URL}/${id}`, { method: 'DELETE' }); if (response.ok) { const newData = agendamentos.filter(agendamento => agendamento.id !== id); setAgendamentos(newData); updateAgendamentos(newData); // 更新全局状态 } else { throw new Error('Erro ao excluir agendamento'); } } catch (error) { console.error("Erro ao excluir agendamento:", error); Alert.alert("Erro", "Ocorreu um problema ao tentar excluir o agendamento."); } }; // ... 其他原有代码 };
4. 在My Appointments页面中使用Context
import { useContext } from 'react'; import { AgendamentoContext } from './AgendamentoContext'; const MeusAgendamentos = () => { const { agendamentos } = useContext(AgendamentoContext); // ... 渲染逻辑和之前一致,直接使用agendamentos即可 };
方案三:本地存储(AsyncStorage)
如果需要在APP重启后仍能看到数据(即使无网络),可以结合AsyncStorage把数据存在本地,同时和后端API同步。
实现步骤:
- 在预约页面中,每次保存/删除预约后,把最新数据存入AsyncStorage
- 在My Appointments页面中,先从AsyncStorage读取数据,再调用API刷新
示例代码:
1. 封装AsyncStorage工具函数
import AsyncStorage from '@react-native-async-storage/async-storage'; export const saveAgendamentos = async (data) => { try { await AsyncStorage.setItem('agendamentos', JSON.stringify(data)); } catch (error) { console.error("Erro ao salvar no storage:", error); } }; export const getAgendamentos = async () => { try { const data = await AsyncStorage.getItem('agendamentos'); return data ? JSON.parse(data) : []; } catch (error) { console.error("Erro ao ler do storage:", error); return []; } };
2. 在预约页面中更新存储
修改fetchAgendamentos和handleDelete:
import { saveAgendamentos } from './storage'; const AgendamentoAdv = () => { // ... 原有代码 const fetchAgendamentos = async () => { try { const response = await fetch(API_URL); const data = await response.json(); setAgendamentos(data); await saveAgendamentos(data); // 保存到本地 } catch (error) { console.error("Erro ao buscar agendamentos:", error); } }; const handleDelete = async (id) => { try { const response = await fetch(`${API_URL}/${id}`, { method: 'DELETE' }); if (response.ok) { const newData = agendamentos.filter(agendamento => agendamento.id !== id); setAgendamentos(newData); await saveAgendamentos(newData); // 更新本地存储 } else { throw new Error('Erro ao excluir agendamento'); } } catch (error) { console.error("Erro ao excluir agendamento:", error); Alert.alert("Erro", "Ocorreu um problema ao tentar excluir o agendamento."); } }; // ... 其他原有代码 };
3. 在My Appointments页面中读取存储
import { getAgendamentos, saveAgendamentos } from './storage'; const MeusAgendamentos = () => { const [agendamentos, setAgendamentos] = useState([]); useEffect(() => { loadAgendamentos(); }, []); const loadAgendamentos = async () => { // 先读取本地存储 const localData = await getAgendamentos(); setAgendamentos(localData); // 再调用API刷新最新数据 try { const response = await fetch(API_URL); const apiData = await response.json(); setAgendamentos(apiData); await saveAgendamentos(apiData); // 更新本地存储 } catch (error) { console.error("Erro ao buscar agendamentos:", error); } }; // ... 渲染逻辑 };
内容的提问来源于stack exchange,提问作者Thabata Dias
相关产品推荐
相关产品推荐

