我希望一旦用户单击提交按钮即可重新加载整个“页面”并调用 useEffect 函数。当前的行为是,当用户单击提交按钮时,根本不会调用 useEffect 函数。就好像提交后没有直接重新加载一样。我不知道这是否是由于async和await造成的。我给你代码:
useEffect():
useEffect(() => {
console.log('test useEffect');
(async () => {
try {
const value = await AsyncStorage.getItem('authToken_Lust');
if(value !== null) {
const decodedValue = jwt_decode(value);
const current_time = Date.now() / 1000;
if(decodedValue.exp < current_time) {
setMessage('Vous n\'êtes plus connecté(e).')
} else {
setMessage('Vous êtes connecté(e)');
}
}
} catch(err) {
console.log(err);
}
})();
}, []);
用户点击提交后调用的函数代码:
const onSubmit = async () => {
setLoading(true)
await fetch('http://192.168.1.36:3000/api/users/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: email,
password: password
})
})
.then((response) => response.json())
.then(async (res) => {
if(res.error) {
setMessage(res.error);
} else {
try {
await AsyncStorage.setItem('authToken_Lust', res.token);
} catch (err) {
console.log(err);
}
}
})
.catch((err) => console.log(err))
.finally(() => setLoading(false));
}
坦克
最佳答案
创建一个状态变量来指示凭证已成功提交(在此组件内)。
const [submitted, setSubmitted] = useState(1);
每当您在 onSubmit 中收到来自 api 的响应时,请更改此状态变量(以某种方式更新组件):
try { await AsyncStorage.setItem('authToken_Lust', res.token); setSubmitted(submitted+1); }
从
useEffect
中完全删除依赖项数组,或更改它以响应提交的
值更改;useEffect(() => { // ... }, [submitted]);
关于javascript - 在React Native中提交后如何调用useEffect中的异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65781098/