提取后无法设置反应
我有一个组件,在成功获取后,我想渲染一些数据,但是即使成功获取后,SetState也无法正常工作。即使是“ console.log(wendesp.data)”也显示了正确的对象,但是为什么“ setGroupData(wendesp.data)”行上方的“ setGroupData(wendesp.data)”行不会更改状态?,而是返回一个空对象。
这是代码:
const GroupContent = ({ groupContent, changeGroupTitle }) => {
const groupId = window.location.href.split(
"http://localhost:3001/groups/"
)[1];
const [groupData, setGroupData] = useState({});
let token = "";
const getGroupData = async () => {
token = await localStorage.getItem("token");
if (token) {
try {
const auth = `Bearer ${token}`;
// console.log(auth);
const response = await axios.get(`/api/groups/${groupId}`, {
headers: {
Authorization: auth,
},
});
console.log(response.data);
setGroupData(response.data);
console.log(groupData);
changeGroupTitle(groupData.title);
} catch (err) {
console.log(err.response);
}
}
};
useEffect(() => {
getGroupData();
}, []);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
SetState工作正常,但是更新本质上是异步的。您可以在此处做几件事
convert
setGroupData(response.data)
tosetGroupData((()=>({... {... response.data}})
>使用
使用
groupData
在依赖性数组中。如果我是您,我会更改的其他一些事情:
fetchgroupdata
,但这是我的个人喜好,前两个指针将有效
The setState is working fine but the update is asynchronous in nature. You can do couple of things here
Convert
setGroupData(response.data)
tosetGroupData(() => ({...response.data}})
Listen to state change using
useEffect
withgroupData
in the depenency array.Here's some other things which I'd change if I were you:
fetchGroupData
But these are my personal preferences, the first two pointers will work