将返回数据的函数传递给 React Native 的 FlatList 数据属性。

huangapple go评论90阅读模式
英文:

Passing a function that returns data to react native FlatList data property

问题

I used the following function inside the Flatlist data property but it is not rendering anything. why? I think an alternative is to set state inside the function and use the state as the flatlist data property, but in that case how do I set state whenever asyncstorage changes?

async function getFlatlistData() {
  try {
    const numbers = await AsyncStorage.getAllKeys();
    numbers.forEach(function myFunction(item, index, arr) {
      arr[index] = JSON.parse(item);
      arr[index]['key'] = Number(arr[index]['key']);
    });
    numbers.sort((a, b) => b.key - a.key);
    console.log("running");
    return numbers;
  } catch (error) {
    alert(error);
  }
}
return (
  </View>
  <FlatList
    data={getFlatlistData()}
    renderItem={({ item }) => <Text>{item.title}</Text>}
    keyExtractor={(item, index) => index.toString()}
  />
  </View>
);

Note: The provided code is in JavaScript, and I have not translated the code itself, only the explanatory text.

英文:

I used the following function inside the Flatlist data property but it is not rendering anything. why? I think an alternative is to set state inside the function and use the state as the flatlist data property, but in that case how do I set state whenever asyncstorage changes?

async function getFlatlistData(){
      try{
        const numbers = await AsyncStorage.getAllKeys();
        //numbers = 
        // [&quot;{\&quot;key\&quot;:\&quot;1678328476308\&quot;,\&quot;title\&quot;:\&quot;Dog\&quot;}&quot;,
        //&quot;{\&quot;key\&quot;:\&quot;1678328921886\&quot;,\&quot;title\&quot;:\&quot;Cat\&quot;}&quot;]
        
  
        numbers.forEach(function myFunction(item, index, arr) {
                          arr[index] = JSON.parse(item);
                          arr[index][&#39;key&#39;] = Number(arr[index][&#39;key&#39;])
                        })
        numbers.sort((a, b) =&gt; b.key - a.key);
        console.log(&quot;running&quot;)
        return numbers

      } catch (error) {
        alert(error)
      }
      
    }
return (
    &lt;/View&gt;
       &lt;FlatList 
          data={getFlatlistData()} 
          renderItem={
            ({item}) =&gt; &lt;Text&gt;{item.title}&lt;/Text&gt;
          } 
          keyExtractor={(item, index) =&gt; index.toString()}
       /&gt;
     &lt;/View&gt;
    );
  }

答案1

得分: 2

以下是代码的翻译部分:

FlatList组件未渲染任何内容因为它接收到的是一个Promise而不是一个数据数组

你需要使用useState来获取数据数组然后再将其分配给FlatList

import React, { useEffect, useState } from 'react';
import { FlatList, Text, View } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

function App() {
  const [data, setData] = useState([]);

  useEffect(() => {
    async function fetchData() {
      try {
        const numbers = await AsyncStorage.getAllKeys();
        const parsedNumbers = numbers.map((item) => JSON.parse(item));
        const sortedNumbers = parsedNumbers.sort((a, b) => b.key - a.key);
        setData(sortedNumbers);
      } catch (error) {
        alert(error);
      }
    }

    fetchData();
  }, []);

  return (
    <View>
      <FlatList
        data={data}
        renderItem={({ item }) => <Text>{item.title}</Text>}
        keyExtractor={(item) => item.key.toString()}
      />
    </View>
  );
}

export default App;
英文:

The FlatList component is not rendering anything because it is receiving a promise instead of an array of data.

You need to use a useState to get the array before assigning to the Flatlist.

import React, { useEffect, useState } from &#39;react&#39;;
import { FlatList, Text, View } from &#39;react-native&#39;;
import AsyncStorage from &#39;@react-native-async-storage/async-storage&#39;;

function App() {
 const [data, setData] = useState([]);

useEffect(() =&gt; {
  async function fetchData() {
    try {
     const numbers = await AsyncStorage.getAllKeys();
     const parsedNumbers = numbers.map((item) =&gt; JSON.parse(item));
     const sortedNumbers = parsedNumbers.sort((a, b) =&gt; b.key - a.key);
     setData(sortedNumbers);
   } catch (error) {
    alert(error);
  }
}

fetchData();
}, []);

return (
 &lt;View&gt;
  &lt;FlatList
    data={data}
    renderItem={({ item }) =&gt; &lt;Text&gt;{item.title}&lt;/Text&gt;}
    keyExtractor={(item) =&gt; item.key.toString()}
  /&gt;
&lt;/View&gt;
);
}

export default App;

答案2

得分: 0

First: 你需要使用 useState 钩子来渲染组件。
Second: 你的异步函数返回的是一个 Promise,而不是一个数组。

import React from 'react';
import { FlatList, Text, View } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

export default function FlatListData() {

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

    const getFlatlistData = async() => {
        try {
            const numbers = await AsyncStorage.getAllKeys();
            if (numbers) {
                const newArr = [...JSON.parse(numbers)];
                newArr.map((obj) => {
                    obj.key = Number(obj.key);
                });
                newArr.sort((a, b) => b.key - a.key);
                setData(newArr);
            }
        } catch (e) {
            throw e;
        }
    }

    React.useEffect(() => {
        getFlatlistData();
    }, []);

    return (
        <FlatList
            data={data}
            renderItem={({ item }) => <Text>{item.title}</Text>}
            keyExtractor={(item, index) => index.toString()}
        />
    );
}
英文:

First: You need to use useState hook to render the components.
Second: Your async function returns promise, not an array.

import React from &#39;react&#39;;
import { FlatList, Text, View } from &#39;react-native&#39;;
import AsyncStorage from &#39;@react-native-async-storage/async-storage&#39;;

export default function FlatListData() {

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

    const getFlatlistData = async() =&gt; {
        try{
            const numbers = await AsyncStorage.getAllKeys();
            if(numbers){
                const newArr = [...JSON.parse(numbers)];
                newArr.map((obj) =&gt; {
                    obj.key = Number(obj.key);
                });
                newArr.sort((a, b) =&gt; b.key - a.key);
                setData(newArr);
            }
        }catch(e){
            throw e;
        }
    }

    React.useEffect(() =&gt; {
        getFlatlistData();
    }, []);

    return (

        &lt;FlatList
        data={data} 
        renderItem={({item}) =&gt; &lt;Text&gt;{item.title}&lt;/Text&gt;} 
        keyExtractor={(i, x) =&gt; x}/&gt;

    );

}

huangapple
  • 本文由 发表于 2023年3月9日 22:45:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75686149.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定