【发布时间】:2020-11-10 09:23:30
【问题描述】:
我有一个应用程序,其中列出了动物慈善机构的事件。
登录后,ong 被定向到您的事件列表,所以我必须通过您的登录页面 ID 来加载此列表。
我正在尝试在函数中加载 AsyncStorage 的变量,然后将其传递给在 React useEffect 中加载事件列表的回调。
代码:
export default function Incidents() {
const [incidents, setIncidents] = useState([]);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(false);
const [id, setID] = useState('');
const [name, setName] = useState('');
加载存储:
loadStorage = async function(callback) {
try {
const ongid = await AsyncStorage.getItem('ongID');
const ongname = await AsyncStorage.getItem('ongName');
if (ongid && ongname !== null) {
setID(ongid);
setName(ongname);
}
} catch (e) {
alert(e);
}
callback();
}
加载事件:
loadIncidents = async function() {
if (loading) {
return;
}
if (total > 0 && incidents.lenght === total) {
return;
}
try {
const response = await api.get('profiles', {
headers: {
Authorization: id,
},
params: { page },
});
setIncidents([ ... incidents, ... response.data]);
setTotal(response.headers['x-total-count']);
setPage(page +1);
setLoading(false);
} catch (e) {
alert(e); //When i access the incident list page i got the error: 'Error: Request failed with status code 400'
}
}
使用效果:
useEffect(() => {
navigation.addListener('focus', () => {
loadStorage(loadIncidents);
});
}, []);
loadIncidents 的alert (e) 行中的错误是因为useEffect 在我第一次进入应用程序时没有完全调用loadStorage (loadIncidents) 部分。
我有另一个名为 newIncident 的页面,如果我在此错误上按 OK 后导航到该页面并返回事件列表页面(navite.goBack ()),该列表将加载来自记录的 ONG 的所有事件。
当我第一次进入列出 ONG 事件的页面时需要这种行为。由于这两种方法都是异步的,我无法弄清楚如何做到这一点。
【问题讨论】:
-
我看到的一个问题是 callback() 应该在 loadStorage 的 if 块内,否则即使 ongid 为空也会调用它
-
已经尝试过了,但没有成功。同样的错误仍然存在。
-
如果你在 loadIncidents 中放了一个 console.log(id) 你会看到一个有效的令牌吗?
-
不,id 为空
-
console.log( 'id': + id ) 在 if 条件为真的 loadStorage 中 try catch 块之后也是空的。
标签: node.js react-native use-effect asyncstorage