【发布时间】:2019-07-03 16:02:00
【问题描述】:
在 useEffect 上加载数据后尝试更新状态。能够更新局部变量但不能更新状态。我正在关注https://www.robinwieruch.de/react-hooks-fetch-data/ 中的一个示例,其中 Robin 以类似的方式设置状态。出于某种原因,在我的情况下,状态变量从未正确设置。
使用 AWS Amplify 加载 graphQL 数据。似乎对局部变量有效,但对状态变量无效。
const [serviceTypes, setServiceTypes] = useState([{}]);
let myServiceTypes = [{}]; // try it with a local variable to debug
useEffect(() => {
let unmounted = false;
async function fetchData() {
const result = await API.graphql(
graphqlOperation(queries.listServiceTypes)
);
console.log(result);
console.log('setting service types...');
console.log(result.data.listServiceTypes.items);
setServiceTypes(result.data.listServiceTypes.items);
myServiceTypes = result.data.listServiceTypes.items;
console.log(myServiceTypes); // set correctly
console.log(serviceTypes); // empty
}
if (!unmounted) {
fetchData();
}
return () => {
unmounted = true;
};
}, []);
期望将 serviceTypes 设置为加载的数据。相反,它是空的。
【问题讨论】:
标签: reactjs react-hooks