我是一個新的開發人員。如果您登錄我們的網站,就會創建 JWT。當我按下按鈕時,我必須將它作為后端放在 API 中。并且如果螢屏成功,API中的地址必須列印出來。如果失敗,螢屏上應顯示“身份驗證失敗”。我想做這個。請幫我。
import axios from 'axios';
import React, { useState } from 'react';
import { Button } from '@material-ui/core';
function TestPage() {
const onLogin = () => {
var variables = {
email: email,
password: password,
};
Axios.post('/auth/login', variables).then((res) => {
setCookie('token', res.payload.accessToken);
setCookie('exp', res.payload.accessTokenExpiresIn);
Axios.defaults.headers.common['Authorization'] = `Bearer ${res.payload.accessToken}`;
Axios.get('/user/me').then((res) => {
console.log(res);
});
});
};
return (
<>
<div>
<Button
variant="contained"
color="primary"
style={{ width: '200px' }}
onClick={(e) => customFetch(e)}>
address
</Button>
</div>
{address && <div>{address}</div>}
</>
);
}
export default TestPage;
uj5u.com熱心網友回復:
通常對于任何網路操作,了解它何時進行、何時完成和/或出現錯誤會很有幫助。讓我們設定一下:
const [isLoading, setIsLoading] = useState(false)
const [data, setData] = useState(null)
const [error, setError] = useState(null)
// inside your `onLogin` function...
setIsLoading(true);
Axios.post('/auth/login', variables).then((res) => {
setCookie('token', res.payload.accessToken);
setCookie('exp', res.payload.accessTokenExpiresIn);
Axios.defaults.headers.common['Authorization'] = `Bearer ${res.payload.accessToken}`;
// bit messy using the same error state for both but you can always refactor
Axios.get('/user/me').then((res) => {
console.log(res);
setData(res); // not sure where the actual data is with Axios
}).catch(err => setError(err);
}).catch(err => setError(err));
setIsLoading(false);
在 POST 期間,相應地設定狀態變數:
- 發帖前,
setIsLoading(true) - 成功時,
setData(response.data) // whatever your payload might be - 在錯誤/失敗時,
setError(error)
現在在您的組件回傳中,您可以有條件地呈現不同的狀態,例如:
// your component body
if (isLoading) return (
// a loading state
)
if (error) return (
// an error state
// e.g. "Authentication Failure"
)
return (
// your success/ideal state
// e.g:
<>
<div>
<Button
variant="contained"
color="primary"
style={{ width: '200px' }}
onClick={(e) => customFetch(e)}>
address
</Button>
</div>
{address && <div>{address}</div>}
</>
)
或者,您可以稍微不同地利用變數:
return (
<>
<div>
<Button
variant="contained"
color="primary"
style={{ width: '200px' }}
onClick={(e) => customFetch(e)}
disabled={isLoading}>
address
</Button>
</div>
<div>
{isLoading
? 'Checking...'
: error !== null
? 'Something went wrong'
: 'Ready to submit'}
</div>
</>
)
不過,三元樣式可能有點混亂。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/397849.html
標籤:javascript 反应 打字稿 材质-ui 下一个.js
