在 Login 组件中,我调用了 login 函数来期望异步行为。
const handleSubmit = async (e) => {
e.preventDefault()
if (usernameRef.current.value === "" || passwordRef.current.value === "") {
return setError('username or password field should not be empty')
}
setError('')
setLoading(true)
try {
const res = await login(usernameRef.current.value, passwordRef.current.value)
localStorage.setItem("token", res.data.access_token)
history.push("/")
setLoading(false)
} catch {
setError('Could not login')
setLoading(false)
}
}
在 authContext 中,我在下面写了这两个:
useEffect(() => {
const unsubscribe = axios.get("http://127.0.0.1:8000/api/users/me", {
headers: {
'Authorization': `Bearer ${localStorage.getItem("token")}`
},
}).then((res) => {
console.log(res.statusText)
setCurrentUser(res.data)
setLoading(false)
}).catch((err) => {
console.log(err)
})
return unsubscribe
}, [])
const login = async (username, password) => {
const details = {
"username": username,
"password": password
}
let formBody = [];
for (let property in details) {
let encodedKey = encodeURIComponent(property);
let encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
return await axios.post("http://127.0.0.1:8000/login", formBody, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
})
}
抓取有问题吗?每当我登录时,它确实登录成功,但出现错误,指示要修复,取消 useEffect 清理函数中的所有订阅和异步任务。