我如何使用react hook的useState存储带有嵌套对象作为属性的对象数组?

时间:2019-09-25 20:49:31

标签: javascript reactjs react-native react-hooks

我正在获取Expense对象的数组,其中包含2个具有as属性的对象,这些对象具有自己的一组对象作为属性。看起来像这样:

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

现在,我想遍历响应数组并将它们添加到我的hook的数据变量中,并已尝试做相应的操作:

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

运行此命令时,出现以下错误:未处理的承诺拒绝:TypeError:散布不可迭代实例的无效尝试

我该如何解决?

编辑:我知道一个选择是访问对象属性并以字符串形式存储它们,但我不希望自己绕开它。建议我使用useReducer,但是我对Hooks并不陌生,还没有弄清楚reducer如何解决这个问题。如果这样,将不胜感激。

1 个答案:

答案 0 :(得分:1)

无视我先前的回答,这是因为您正在将 object 存储在data变量中,但是当您将其视为 array 时尝试传播它。

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

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

应该解决您的问题。然后将data.expenses.map替换为data.map,将writeData(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)
      });
    });
  });
}