如何在之后立即引用useState设置的值


Continuous React.useState((setter不起作用。
const [balance, setBalance] = React.useState(0);
const [campaigns, setCampaigns] = React.useState([]);
React.useEffect(() => {
console.log('first use Effect');
getRequest(`/api/v1/tablet/campaigns/) // getRequest return Promise Obj
.then(result => {
console.log(result); // [{...},{...},・・・,{...}]
setCampaigns(result);
console.log(campaigns); // [] this is problem part
});
}, []);

如何在之后立即引用useState设置的值?

您必须使用您设置的值,直到组件的下一次刷新,因为状态仅在重新发送时更新

您需要在单独的useEffect中跟踪它,在那里您会收到更新的值:

useEffect(() => {
console.log(campaigns);
}, [campaigns])

另一种选择是使用在状态上设置的值,而不是实际状态值:

React.useEffect(() => {
console.log('first use Effect');
getRequest(`/api/v1/tablet/campaigns/) // getRequest return Promise Obj
.then(result => {
console.log(result); // [{...},{...},・・・,{...}]
setCampaigns(result);
console.log(result); // Access the result here, which is the same as campaigns
});
}, []);

实际上它是有效的,因为setCampaigns是异步的,所以在控制台中看不到活动。

const [balance, setBalance] = React.useState(0);
const [campaigns, setCampaigns] = React.useState([]);
React.useEffect(() => {
console.log('first use Effect');
getRequest(`/api/v1/tablet/campaigns/) // getRequest return Promise Obj
.then(result => {
console.log(result); // [{...},{...},・・・,{...}]
setCampaigns(result);//this function works
console.log(campaigns); // but setCampaigns function works async
});
}, []);

如果你想立即访问它,你需要写下面的代码,这意味着当更改活动对象时会自动触发使用效果功能

React.useEffect(() => {         
console.log(campaigns); // you can see your state data
});
}, [campaigns]);

相关内容

  • 没有找到相关文章

最新更新