如何使用 react hook 的 useState 将包含嵌套对象的对象数组存储为属性?



我正在获取一个 Expense 对象数组,其中包含 2 个对象作为属性,这些对象包含自己的一组对象作为属性。这是它的样子:

{
"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
},
]

现在我想遍历响应数组并将它们添加到我的钩子的数据变量中,并尝试相应地执行以下操作:

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)
});
});
});
} 

最后,这是我的架构的样子:

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?"
}
};

当我运行它时,我收到以下错误:未处理的承诺拒绝:类型错误:无效尝试传播不可迭代实例

我该如何解决这个问题?

编辑:我知道一个选项是访问对象属性并以字符串形式存储它们,但我不想解决这个问题。有人建议我使用 useReducer,但我是 Hooks 的新手,还没有弄清楚 reducer 如何解决这个问题。如果是这样的话,举个例子将不胜感激。

忽略我之前的回答,这是因为您将对象存储在data变量中,但是当您尝试传播它时,您将其视为数组

我建议将费用数组存储在其自己的单独状态中,因为您目前没有其他数据。

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

应该解决你的问题。然后将data.expenses.map替换为data.mapwriteData(result.data)替换为writeData(result.data.expenses).

一起:

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)
});
});
});
} 

相关内容

  • 没有找到相关文章

最新更新