首页 > 解决方案 > React Native FlatList 组件没有渲染我的数组

问题描述

所以,我正在尝试使用 react-native 制作一个应用程序,我需要一个列表,我正在使用 FlatList。当我使用console.log()时,问题似乎出在保存中(我在不同的文件(屏幕)中保存和检索,这可能是问题吗?)。我从异步存储中获取我的数组:

try {
  if ((await AsyncStorage.getItem("DA")) !== null) {
    DUES = JSON.parse(await AsyncStorage.getItem("DA"));
    Works = JSON.parse(await AsyncStorage.getItem("WA"));
    await AsyncStorage.removeItem("DA");
    await AsyncStorage.removeItem("WA");
  }
  if ((await AsyncStorage.getItem("DUES")) !== null) {
    DUES.push(await AsyncStorage.getItem("DUES"));
    Works.push(await AsyncStorage.getItem("Info"));
    await AsyncStorage.removeItem("DUES");
    await AsyncStorage.removeItem("Info");
  }
  await AsyncStorage.setItem("DA", JSON.stringify(DUES));
  await AsyncStorage.setItem("WA", JSON.stringify(Works));
} catch (err) {
  console.log(err);
}

我需要在列表中显示它,但没有任何渲染。清单代码:

<FlatList>
      data={Works}
      renderItem=
      {() => {
        <Card>
          <Text>{Works[i]}</Text>
          <Text>Due: {DUES[i]}</Text>
        </Card>;
        i++;
      }}
</FlatList>

保存脚本:

      onPress={async () => {
        try {
          await AsyncStorage.multiSet([
            ["DUES", D],
            ["Info", Title],
          ]);
          console.log("DONE2");
          Alert.alert("Saved!");
        } catch (err) {
          console.log(err);
        }
      }}

这可能是因为我错过了“钥匙”,但 idk。我应该如何解决这个问题?,并使其呈现列表。有一个更好的方法吗?

标签: javascriptreact-native

解决方案


这是因为您没有返回需要在 FlatList 组件的 renderItem 方法中打印出来的元素。而是试试这个:

<FlatList>
      data={Works}
      renderItem=
      {({ item, index }) => {
        return (
          <Card>
            <Text>{item}</Text>
            <Text>Due: {DUES[index]}</Text>
          </Card>
        );
      }}
</FlatList>

推荐阅读