如何通过 axios 获取 useState 中的数据和反应功能组件
how to get, by a get from axios, data in useState with react functionnal component
我正在处理由 jhipster 生成的 React 项目。
当我从休息时执行获取请求时 api.
GET http://localhost:8080/api/account
Accept: */*
Cache-Control: no-cache
Authorization: Bearer bearerValue
我得到了答案:
HTTP/1.1 200 OK
Expires: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
X-XSS-Protection: 1; mode=block
Pragma: no-cache
X-Frame-Options: DENY
Referrer-Policy: strict-origin-when-cross-origin
Content-Security-Policy: default-src 'self'; frame-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://storage.googleapis.com; style-src 'self' https://fonts.googleapis.com 'unsafe-inline'; img-src 'self' data:; font-src 'self' https://fonts.gstatic.com data:
Date: Sun, 05 Apr 2020 18:26:07 GMT
Connection: keep-alive
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
X-Content-Type-Options: nosniff
Feature-Policy: geolocation 'none'; midi 'none'; sync-xhr 'none'; microphone 'none'; camera 'none'; magnetometer 'none'; gyroscope 'none'; speaker 'none'; fullscreen 'self'; payment 'none'
Transfer-Encoding: chunked
Content-Type: application/json
{
"id": 3,
"login": "admin",
"firstName": "Administrator",
"lastName": "Administrator",
"email": "admin@localhost",
"imageUrl": "",
"activated": true,
"langKey": "fr",
"createdBy": "system",
"createdDate": null,
"lastModifiedBy": "system",
"lastModifiedDate": null,
"authorities": [
"ROLE_USER",
"ROLE_ADMIN"
]
}
表示 API 可以。
我的问题是如何在我的状态下从 axios promise 获得结果,
只执行一个请求。
这是我尝试进行的方式。
portfolio.tsx
export interface IPortfolioProps extends StateProps,
DispatchProps,
RouteComponentProps<{ url: string }> {
}
export interface AccountState {
id: number,
login: string,
firstName: string,
lastName: string,
email: string,
imageUrl: string,
activated: boolean,
langKey: string,
createdBy: string,
createdDate: string,
lastModifiedBy: string,
lastModifiedDate: string,
authorities: Array<string>
}
export const Portfolio = (props: IPortfolioProps) => {
const currentAccountState = async (): Promise<AccountState> => {
return await axios.get<AccountState>(`/api/account`)
.then((response) => {
return response.data
});
};
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
const isAdmin: boolean = () => {
let as: AccountState;
currentAccountState()
.then(response => {
as = response;
// eslint-disable-next-line no-console
console.log('as : ', as);
return as.authorities.find(
authority => authority === AUTHORITIES.ADMIN) !== undefined;
});
};
const [admin, setAdmin] = useState(isAdmin);
return (
<div>
{`admin : ${admin}`}
</div>);
}
当 运行 我总是在屏幕上显示 "admin : undefined" 的应用程序时,
而我的控制台登录显示正确的帐户预期帐户。
我想要的是将布尔答案保存为当前用户是管理员的状态,
处于管理状态。
我认为这是因为 admin
没有默认值,所以 admin
是 undefined
当页面第一次呈现之前你从 API.最好先用默认值初始化它,在挂载时调用 API,然后用响应更新状态。
您可以尝试类似的方法:
const [admin, setAdmin] = useState(null);
useEffect(() => {
if (!admin) {
const currentAccountState = async (): Promise<AccountState> => {
return await axios.get<AccountState>(`/api/account`)
.then((response) => {
return response.data
});
};
currentAccountState()
.then(response => {
console.log('as : ', response );
// probably add better handling here in the case that there is no result in the find, otherwise you mightrun into the same issue if admin is undefined again
setAdmin(response.authorities.find(authority => authority === AUTHORITIES.ADMIN) !== undefined);
});
}
}, [admin])
return (
<div>
{`admin : ${admin}`}
</div>
);
我正在处理由 jhipster 生成的 React 项目。 当我从休息时执行获取请求时 api.
GET http://localhost:8080/api/account
Accept: */*
Cache-Control: no-cache
Authorization: Bearer bearerValue
我得到了答案:
HTTP/1.1 200 OK
Expires: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
X-XSS-Protection: 1; mode=block
Pragma: no-cache
X-Frame-Options: DENY
Referrer-Policy: strict-origin-when-cross-origin
Content-Security-Policy: default-src 'self'; frame-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://storage.googleapis.com; style-src 'self' https://fonts.googleapis.com 'unsafe-inline'; img-src 'self' data:; font-src 'self' https://fonts.gstatic.com data:
Date: Sun, 05 Apr 2020 18:26:07 GMT
Connection: keep-alive
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
X-Content-Type-Options: nosniff
Feature-Policy: geolocation 'none'; midi 'none'; sync-xhr 'none'; microphone 'none'; camera 'none'; magnetometer 'none'; gyroscope 'none'; speaker 'none'; fullscreen 'self'; payment 'none'
Transfer-Encoding: chunked
Content-Type: application/json
{
"id": 3,
"login": "admin",
"firstName": "Administrator",
"lastName": "Administrator",
"email": "admin@localhost",
"imageUrl": "",
"activated": true,
"langKey": "fr",
"createdBy": "system",
"createdDate": null,
"lastModifiedBy": "system",
"lastModifiedDate": null,
"authorities": [
"ROLE_USER",
"ROLE_ADMIN"
]
}
表示 API 可以。 我的问题是如何在我的状态下从 axios promise 获得结果, 只执行一个请求。
这是我尝试进行的方式。
portfolio.tsx
export interface IPortfolioProps extends StateProps,
DispatchProps,
RouteComponentProps<{ url: string }> {
}
export interface AccountState {
id: number,
login: string,
firstName: string,
lastName: string,
email: string,
imageUrl: string,
activated: boolean,
langKey: string,
createdBy: string,
createdDate: string,
lastModifiedBy: string,
lastModifiedDate: string,
authorities: Array<string>
}
export const Portfolio = (props: IPortfolioProps) => {
const currentAccountState = async (): Promise<AccountState> => {
return await axios.get<AccountState>(`/api/account`)
.then((response) => {
return response.data
});
};
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
const isAdmin: boolean = () => {
let as: AccountState;
currentAccountState()
.then(response => {
as = response;
// eslint-disable-next-line no-console
console.log('as : ', as);
return as.authorities.find(
authority => authority === AUTHORITIES.ADMIN) !== undefined;
});
};
const [admin, setAdmin] = useState(isAdmin);
return (
<div>
{`admin : ${admin}`}
</div>);
}
当 运行 我总是在屏幕上显示 "admin : undefined" 的应用程序时, 而我的控制台登录显示正确的帐户预期帐户。 我想要的是将布尔答案保存为当前用户是管理员的状态, 处于管理状态。
我认为这是因为 admin
没有默认值,所以 admin
是 undefined
当页面第一次呈现之前你从 API.最好先用默认值初始化它,在挂载时调用 API,然后用响应更新状态。
您可以尝试类似的方法:
const [admin, setAdmin] = useState(null);
useEffect(() => {
if (!admin) {
const currentAccountState = async (): Promise<AccountState> => {
return await axios.get<AccountState>(`/api/account`)
.then((response) => {
return response.data
});
};
currentAccountState()
.then(response => {
console.log('as : ', response );
// probably add better handling here in the case that there is no result in the find, otherwise you mightrun into the same issue if admin is undefined again
setAdmin(response.authorities.find(authority => authority === AUTHORITIES.ADMIN) !== undefined);
});
}
}, [admin])
return (
<div>
{`admin : ${admin}`}
</div>
);