sqlite 在我的React Native应用程序中获取数据返回[object Object]而不是renderSectionHeader

z8dt9xmd  于 8个月前  发布在  SQLite
关注(0)|答案(2)|浏览(95)

我遇到了一个问题,而试图从一个API URL获取数据,问题是,数据没有返回的类别标题在SectionList中,而不是我有数据返回的标题下[object Object],而不是renderSectionHeader
我的问题再现小吃博览会:https://snack.expo.dev/@fyardlest/resto-app?platform=android

bkhjykvo

bkhjykvo1#

您的数据类型架构与SectionList要求不匹配。请看一下给出的链接。您的数据模式如下所示:

[
  { category: {title: 'Appetizers'}, id: 1, price: "10", title: "Spinach Artichoke Dip" },
  ~~~
  ~~~
]

SectionList组件预期如下:

[
  {
    title: 'Main dishes',
    data: ['Pizza', 'Burger', 'Risotto'],
  },
]

除了第一个数组级别之外,SectionList还需要更深一层。所以我认为你应该使用FlatList
但是,主要问题来自saveMenuItems函数:

export function saveMenuItems(menuItems) {
  db.transaction((tx) => {
    const values = menuItems
      .map(
        (item) =>
          `('${item.id}', '${item.title}', '${item.price}', '${item.category}')`
      )
      .join(', ');

    tx.executeSql(
      `insert into menuitems (uuid, title, price, category) values ${values};`
    );
  });
}

这个函数将category变成[object Object],因为你使用了${item.category},而item.categorty是这样的对象:{ title: 'something' }。然后在getSectionListData内部,问题本身出现,并产生另一个问题。
我认为你应该在saveMenuItems函数中使用${item.category.title}

bhmjp9jg

bhmjp9jg2#

我还修改了获取数据的方式,它也可以工作。以下是我通过设置类别所做的工作:

const fetchData = async () => {
try {
  const response = await fetch(API_URL);

  if (!response.ok) {
    throw new Error('Failed to fetch data');
  }

  const data = await response.json();

  // here is the way I retrieve the category title

  menuItems = data.menu.map((item) => ({
    ...item,
    category: item.category.title
  }))

  return menuItems
} catch (error) {
  console.error('Error fetching data:', error);
  return [];
}

};

相关问题