我的响应数据未存储到React JS中的变量中
我正在尝试将响应数据存储到activationType
变量中,在使用效率的内部,我正在基于TABS值来循环API,API将返回值true
或<代码> false ,我能够在控制台上获取值,但是当我尝试存储数据时,我会得到空数组。
const tabs = [
// {value: 'All', label: `${i18n.t('AllActivity')}`},
{value: 'ActSendGift', label: `${i18n.t('Gifts')}`},
{value: 'ActSubscribe', label: `${i18n.t('Subscribers')}`},
{value: 'ActFollow', label: `${i18n.t('Followers')}`},
];
const activityType: any = [];
useEffect(() => {
async function fetchData() {
return tabs.map(async (item: any) => {
return await Api.user
.getSettingValues(item.value)
.then((response: any) => {
// console.log(response.settingValue); // true
// console.log(item.value); "ActSendGift"
return activityType.push(response.settingValue);
});
});
}
fetchData();
}, [activityFeedData.activityList, activityType]);
I am trying to store my response data into the activityType
variable, inside the useEffect I am looping an API based on tabs value, the API will return is the value true
or false
, and I am able to get the values on my console but when I try to store the data I am getting empty array.
const tabs = [
// {value: 'All', label: `${i18n.t('AllActivity')}`},
{value: 'ActSendGift', label: `${i18n.t('Gifts')}`},
{value: 'ActSubscribe', label: `${i18n.t('Subscribers')}`},
{value: 'ActFollow', label: `${i18n.t('Followers')}`},
];
const activityType: any = [];
useEffect(() => {
async function fetchData() {
return tabs.map(async (item: any) => {
return await Api.user
.getSettingValues(item.value)
.then((response: any) => {
// console.log(response.settingValue); // true
// console.log(item.value); "ActSendGift"
return activityType.push(response.settingValue);
});
});
}
fetchData();
}, [activityFeedData.activityList, activityType]);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用“ Usestate”钩子,而不是在React中声明变量。
首先,您需要导入钩子
和功能组件内部,可以在获取数据后更新状态。
USESTATE挂钩返回两个值,一个是状态变量,第二个是状态更新函数。该组件将随着状态的变化自动重新渲染。
you can use 'useState' hook instead of declaring a variable in react.
first you need to import the hook
and inside your functional component you can update the state after fetching the data.
The useState hook returns two values, One is the state variable and the second one is the state update function. The component will re-render automatically as the state changes.
尝试将此数组放入状态,并确保正在更新Usefct依赖项数组中的变量,以便执行此块。
Try putting this array into a state and ensure that the variables that are in the usefct dependency array are being updated so that this block is executed.