我正在获取一组 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)
});
});
});
}
当我运行它时,我收到以下错误:未处理的承诺拒绝:类型错误:传播不可迭代实例的无效尝试
我该如何解决这个问题?
编辑: 我知道一个选项是访问对象属性并将它们以字符串化的形式存储,但我不想绕过这个。有人建议我使用 useReducer,但我是 Hooks 的新手,还没有弄清楚减速器如何解决这个问题。如果是这样,一个例子将不胜感激。
墨色风雨
相关分类