reactjs - 如何在 useState “React” 内的对象中推送 For 循环
问题描述
我需要在 useState 中推送对象:
const [getData, setGetData] = useState({});
const data = {
name: ["My Name"],
age: ["33 Years"],
address: ["My Address"]
}
useEffect(() => {
if (data) {
for (const input in data) {
if (Error.hasOwnProperty(input)) {
setGetData({...getData, [input]: data[input][0]});
}
}
}
}, [data]);
console.log(getData);
我尝试显示它,但我发现“getData”为空{}
解决方案
如果您知道您的对象将拥有什么样的键,那么您可以指定它
const [getData, setGetData] = useState({}); // change this to useReducer instead?
因此,您可以使用 useReducer(在 reactjs.org 上查找)代替您的代码,但由于您使用的是 useState,我将使用它。
const [getData, setGetData] = useState({name:'',age:'',address:''});
您在这里尝试做的是创建一个具有三个键name
、age
和的对象address
。我在这里看到的问题不是添加一个字符串作为值,而是添加一个带有字符串的数组"My Name"
。我不知道您是否希望用户拥有多个姓名或年龄。地址部分我可以理解,但通常你有一个主地址,然后是一个辅助地址。因此,我建议您查找数据结构。
const data = {
name: ["My Name"], // 1
age: ["33 Years"],
address: ["My Address"]
}
这就是我构建数据的方式
const data = {
name: "My Name", // 1
age: 33, // I would change this to a date such as 1999-12-01 instead of just '33'
primaryAddress: "My Address",
secondaryAddress: "My Address",
}
然后我们来到第二部分
useEffect(() => {
if (data) { // You should move this to a function instead, much cleaner
for (const input in data) { // If you have an object you don't need to loop over them and add each key and value pare.
if (Error.hasOwnProperty(input)) {
setGetData({...getData, [input]: data[input][0]});
}
}
}
}, [data]);
我会这样做:
useEffect(() => {
setGetData(data)
},[data])
推荐阅读
- c# - 在 C# 代码中使用 Sharepoint 365 现代体验获取运行时错误
- javascript - JavaScript:等待递归树完成,其中每个递归级别都是 API 调用
- mysql - 在特定时间范围内返回数据并显示它
- javascript - 想在 TypeORM 中创建新记录时保存和插入有什么区别
- c# - 无法将 acrobat COM 组件添加到 .NET 5.0 winform 项目
- wordpress - 根据日期和时间显示文本
- php - 为什么 $stmt->fetch(PDO::FETCH_NUM); 是否返回具有数字索引和列名的数组?
- python - 使用数据包速率查找数据速率
- python - Decentraland - API 请求
- sql - 尝试按日期选择时条件表达式中的数据类型不匹配