我们有一个 ReactJS 应用程序,想要在 API 端验证保存的 JWT 令牌。对于在 App.tsx 中添加等待 axiosClient.post("${URL}/AuthenticateUser/ValidateToken") ,它会抛出错误。
index.tsx:
const msalInstance = new PublicClientApplication(msalConfig);
const container = document.getElementById('root');
const root = createRoot(container!);
root.render(
<MsalProvider instance={msalInstance}>
<App />
</MsalProvider>,
);
module.hot?.accept();
App.tsx:
async function App() {
let isAuthenticated = false;
const url = `${URL}/AuthenticateUser/ValidateToken`;
if (localStorage.getItem('token')) {
await axiosClient.post(url).then((result) => {
/* Do Something */
});
}
axiosClient.tsx:
export const axiosClient = axios.create({
baseURL: URL,
timeout: 300000,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${getToken()}`,
},
});
错误:
TS2786: 'App' cannot be used as a JSX component.
Its return type 'Promise<Element>' is not a valid JSX element.
您不应该将 async 关键字添加到 React 组件本身。相反,你应该做这样的事情
function App() {
const [isAuthenticated, setIsAuthenticated] = React.useState(false);
React.useEffect(() => {
const getToken = async () => {
const url = `${URL}/AuthenticateUser/ValidateToken`;
if (localStorage.getItem('token')) {
await axiosClient.post(url).then(result => {
/* Do Something */
//Set this wherever you need it
setIsAuthenticated(true);
});
}
};
getToken();
}, []);
}