javascript - 更改我的嵌套状态 React Native 时出现问题
问题描述
我的应用程序中有一个状态,如下所示:
const [companyCategories, setCompanyCategories] = useState({ loading: true, categories: null });
我从 API 获取我的类别并设置我的类别,如下所示:
const fetchCategories = useCallback(() => {
fetch(***link***)
.then(res => {
if (!res.ok) {
throw new Error('Failed to fetch.');
}
return res.json()
})
.then(data => {
setCompanyCategories({
loading: false, categories: data.map((el, index) => {
return {
id: el.id,
title: el.title,
selected: false
}
})
})
})
.catch(err => {
console.log(err);
});
}, []);
如果我companyCategories
在那之后记录我的:
Object {
"categories": Array [
Object {
"id": 7,
"selected": false,
"title": "Casual",
},
Object {
"id": 8,
"selected": false,
"title": "Coffe Table",
},
Object {
"id": 10,
"selected": false,
"title": "Dining Table",
},
Object {
"id": 11,
"selected": false,
"title": "Workstation",
},
],
"loading": false,
}
这是我的问题:考虑我将此类别显示为应用程序 UI 的按钮,当用户点击每个类别时,它会通过颜色更改,我需要更改selected
类别的属性,true
默认情况下所有这些都是 false 意味着没有选择. 为此,我编码如下:
const onRadioBtnClick = (item) => {
let updatedState = companyCategories.categories.map((el) => {
if (el.id == item.id) {
return {
...el,
loading: true,
categories: {
...el.categories,
selected: !el.selected
}
}
}
setCompanyCategories(updatedState)
});
};
这不起作用,updatedState 正在向我展示undefined
。如何操纵嵌套状态的一个属性?
解决方案
你放setCompanyCategories(updatedState)
错了线。
它应该是
const onRadioBtnClick = (item) => {
let updatedState = companyCategories.categories.map((el) => {
if (el.id == item.id) {
return {
...el,
loading: true,
categories: {
...el.categories,
selected: !el.selected
}
}
}
});
setCompanyCategories(updatedState);
};
推荐阅读
- python - 如何将 lineEdit 与定义变量的函数连接起来?
- python - “其他”声明没有响应
- java - 在共享库中为 JPA Entity(域类型对象)创建基类的缺点
- javascript - Onclick 按钮,我需要使用 React Hooks 捕获日期值
- c++ - 具有非虚拟成员的类的装饰器
- android - StaggeredGridLayoutManager 重新排序项目而不考虑定义的边距
- xml - 使用同一级别的另一个元素的值获取元素值的正确 XPath 语法是什么?
- javascript - puppeteer:在 DevTools 的网络选项卡中获取特定请求的 JSON 响应
- c# - SQLite 递归查询以获取树的第一个分支
- c - 服务器套接字第一次没有收到消息。为什么会这样?