简体   繁体   English

如何使用 React hook 的 useState 将具有嵌套对象的对象数组存储为属性?

[英]How do I store an array of objects with nested objects as attributes using react hook's useState?

I am fetching an array of Expense objects that contains 2 objects with as attributes that contain their own set of objects as attributes.我正在获取一个包含 2 个对象的 Expense 对象数组,这些对象的属性包含他们自己的一组对象作为属性。 This is what it looks like:这是它的样子:

{
"expenses": [
    {
        "id": "5b996064dfd5b783915112f5",
        "amount": {
            "value": "1854.99",
            "currency": "EUR"
        },
        "date": "2018-09-10T02:11:29.184Z",
        "merchant": "Burger King",
        "receipts": [],
        "comment": "",
        "category": "",
        "user": {
            "first": "Vic",
            "last": "Rob",
            "email": "Vic@rob.com"
        },
        "index": 0
    },
    {
        "id": "5b99606474ab17b7820b3922",
        "amount": {
            "value": "3222.88",
            "currency": "GBP"
        },
        "date": "2018-08-13T07:11:01.680Z",
        "merchant": "McD",
        "receipts": [],
        "comment": "",
        "category": "",
        "user": {
            "first": "craig",
            "last": "Michael",
            "email": "craig@craig.com"
        },
        "index": 1
    },
]

Now I want to iterate through the response array and add them my hook's data variable and have attempted to do accordingly:现在我想遍历响应数组并将它们添加到我的钩子的数据变量中,并尝试做相应的事情:

  const [data, setData] = useState({expenses:[]});
 const Realm = require("realm");
useEffect(() => {
const fetchData = async () => {
  const result = await axios(
   'http://localhost:3000/expenses?limit=10&offset=0',
  );
  writeData(result.data)
};
fetchData();
}, []);

const writeData = data =>{
Realm.open({
schema: [ExpenseSchema, UserSchema, AmountSchema]
}).then(realm => {
realm.write(() => {
  data.expenses.map((expense) => {
    realm.create ('expense',expense)
   setData ([...data, expense]);  //returns an error. same if i use Object.values(expense)
   console.log (expense)
    });
});
});
} 

and lastly, here is what my schema looks like:最后,这是我的架构的样子:

const AmountSchema = {
 name: "amount",
properties: {
value: "string",
currency: "string"
}
};

    const UserSchema = {
  name: "user",
  properties: {
    first: "string",
    last: "string",
    email: "string"
  }
};
const ExpenseSchema = {
  name: "expense",
  primaryKey: "id",
  properties: {
    id: "string",
    amount: "amount?",
    user: "user?",
    date: "date",
    merchant: "string",
    receipt: "data?"
  }
};

When I run this, I get the following error: Unhandled promise rejection: TypeError: Invalid attempt to spread non-iterable instance当我运行它时,我收到以下错误:未处理的 promise 拒绝:TypeError: Invalid attempt to spread non-iterable instance

How do I get around this?我该如何解决这个问题?

EDIT: I know one options is the access the object attributes and store them in a stringified form, but I'd prefer not to hack my way around this.编辑:我知道一个选项是访问 object 属性并将它们以字符串形式存储,但我不想绕过这个。 I was suggested to use useReducer but I am new to Hooks and havn't yet figured out how a reducer would solve this.有人建议我使用 useReducer,但我是 Hooks 的新手,还没有弄清楚减速器如何解决这个问题。 If this is the way, an example would be greatly appreciated.如果是这样,一个例子将不胜感激。

Disregard my previous response, this is because you're storing an object in your data variable, but you are treating it as an array when you try to spread it.忽略我之前的回复,这是因为您将object存储在data变量中,但是当您尝试传播它时将其视为数组

I'd recommend storing the expenses array in its own separate piece of state, seeing as you currently have no other data there.我建议将费用数组存储在单独的 state 中,因为您目前没有其他数据。

const [data, setData] = useState([]);

Should fix your problem.应该解决你的问题。 And then replace data.expenses.map with data.map and writeData(result.data) with writeData(result.data.expenses) .然后将data.expenses.map替换为data.map并将writeData(result.data)替换为writeData(result.data.expenses)

All together:全部一起:

const [data, setData] = useState([]);
const Realm = require("realm");
useEffect(() => {
  const fetchData = async () => {
    const result = await axios(
        'http://localhost:3000/expenses?limit=10&offset=0',
    );
    writeData(result.data.expenses)
  };
  fetchData();
}, []);

const writeData = data =>{
  Realm.open({
    schema: [ExpenseSchema, UserSchema, AmountSchema]
  }).then(realm => {
    realm.write(() => {
      data.map((expense) => {
        realm.create ('expense',expense)
        setData ([...data, expense]);  //returns an error. same if i use Object.values(expense)
        console.log (expense)
      });
    });
  });
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM