首页 > 解决方案 > 如何在 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”为空{}

标签: reactjsreact-hooksuse-effectuse-state

解决方案


如果您知道您的对象将拥有什么样的键,那么您可以指定它

const [getData, setGetData] = useState({}); // change this to useReducer instead?

因此,您可以使用 useReducer(在 reactjs.org 上查找)代替您的代码,但由于您使用的是 useState,我将使用它。

const [getData, setGetData] = useState({name:'',age:'',address:''});

您在这里尝试做的是创建一个具有三个键nameage和的对象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])


推荐阅读