我有一些问题。当我做异步获取数据(使用axios抓取)useEffect,我安上数据状态后,使用useState钩。在页面渲染之前,我得到了服务器的响应。为了演示这个问题,我将console.log用于获取当前状态,并且我得到'undefined':
const [positions, setPositions] = useState([]);
useEffect(() => {
const fetchPositions = async () => {
const response = await EmployeeService.getEmployeePositions();
setPositions(response.data);
};
fetchPositions();
console.log('positions from state: ', positions); //undefined
}, []);
从"EmployeeService"获取数据的方法:
getEmployeePositions(){
return axios.get(EMPLOYEE_API_BASE_URL + '/positions');
}
提前感谢,并致以最诚挚的问候!
React需要重新渲染来显示结果。这意味着您需要捕获setState导致的后续重新呈现的结果。将控制台日志移到useEffect
之外const [positions, setPositions] = useState([]);
useEffect(() => {
const fetchPositions = async () => {
const response = await EmployeeService.getEmployeePositions();
setPositions(response.data);
};
fetchPositions();
}, []);
console.log('positions from state: ', positions); // NOT UNDEFINED
在你有数据之前,React总是渲染一次。所以你可以用条件捕获它。
if (positions.length === 0) {
return null;
}
你的代码没有问题,useEffect总是未定义的,因为它读取渲染应用程序的第一个值。要在useEffect中更新状态,请将参数放在数组[]上,但在您的情况下,它将导致无限循环。
尝试在async函数中记录日志
const [positions, setPositions] = useState([]);
useEffect(() => {
const fetchPositions = async () => {
const response = await EmployeeService.getEmployeePositions();
setPositions(response.data);
console.log('data from response: ', response);
};
fetchPositions();
}, []);
或者像这样做
const [positions, setPositions] = useState([]);
useEffect(() => {
const fetchPositions = async () => {
const response = await EmployeeService.getEmployeePositions();
setPositions(response.data);
console.log('data from response: ', response);
};
if((positions ?? []).length == 0){
fetchPositions();
console.log('this is position state before fetch~>',positions)
} else{
console.log('this is position state after fetch~>',positions)
}
}, [positions]);