【发布时间】:2020-08-08 09:15:14
【问题描述】:
如果我在函数中使用变量而不是使用反应状态对象,那么获取的行为会很奇怪。如果我删除了 const 响应.....和 const data.... 行的东西工作得很好,但如果我使用 fetch 函数并使用普通变量而不使用状态,这不起作用。这是为什么呢?
Object is showing normal if i log it from inside the function
Object is also showing normal if i use const variable
Object is showing like an empty object if i log it from outside the function
但是这段代码工作得很好..
const [services, setServices] = useState([]);
useEffect(() => {
const API_URL = "http://localhost:8080/getServiceName/3";
const loadData = async () => {
const apiData = [];
const response = await fetch(API_URL);
const data = await response.json();
data.services.map(service => (
apiData.push(service.service_name)
));
setServices(apiData);
}
loadData();
}, [location])
请注意,我可以为 const 变量添加更多值(代码中的 const dummyLocation{in image} 和 const apiData)!,如何??
【问题讨论】:
-
请编辑您的问题并具体描述每次尝试的结果
-
当您尝试扩展对象时,您自己表明它确实在 console.log 中有数据。它在非扩展视图中显示为空白,因为 console.log 是同步的,并且在执行时它不包含任何数据。当异步调用 get resolved 时,它会用所有数据填充 dummyLocation。
标签: reactjs javascript-objects