我正在 React 组件中调用我的 API。我正在使用 useState 钩子。我可以进行 API 调用并设置我的状态。当我在设置状态后 console.log 时,它返回未定义状态。我的代码如下:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { API } from '../../config';
import Layout from '../../components/Layout';
const PendingUser = () => {
const [pendingUser, setPendingUser] = useState({
firstName: '',
lastName: '',
email: '',
leAgency: ''
});
useEffect(() => {
getPendingUsers();
}, []);
const getPendingUsers = async () => {
const { data } = await axios.get(`${API}/admin/pendinguser`);
const pendingUsers = data;
setPendingUser({
firstName: pendingUsers.firstName,
lastName: pendingUsers.lastName,
email: pendingUsers.email,
leAgency: pendingUsers.leAgency
});
console.log(pendingUser);
};
return (
<table style={{ width: '100%' }}>
<thead>
<tr>
<td>First Name</td>
</tr>
</thead>
<tbody>
<tr>
<td>{pendingUser.firstName}</td>
</tr>
</tbody>
</table>
);
};
export default PendingUser;
答案 0 :(得分:0)
setPendingUser
调用是异步完成的。这就是为什么在您拨打电话后您不会立即获得 pendingUser
中的值。
如果您想知道每次渲染的状态,我建议将 console.log
放在 return
之前:
console.log(pendingUser);
return (
<table style={{ width: '100%' }}>