如何在 useState “React” 中的对象中推送 For 循环

How to Push For Loop in Object inside useState “React”

我需要在 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:''});

您在这里尝试做的是创建一个具有三个键 nameageaddress 的对象。我在这里看到的问题不是添加一个字符串作为值,而是添加一个带有字符串 "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])