最佳方法从 JSON API 中附加数据 React Native

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

Best Way to Append data from json api React Native

问题

在主屏幕上,我从JSON API获取数据并附加到数据状态变量。每次API调用都会提供10次。但问题是,在达到50-60个项目之后,应用程序变得非常慢(甚至在移动设备上冻结1-2分钟)。当我尝试找出问题时,对每个项目的迭代进行了控制,我发现在将数据附加到“setData”状态时发生了不必要的重新渲染。请查看下面的详细问题:

import React, { useState, useEffect } from 'react';
import { View, Text, Button, FlatList } from 'react-native';

const API_URL = 'https://my-api-url.com/data';

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

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    try {
      const response = await fetch(API_URL);
      const jsonData = await response.json();
      setData(jsonData);
    } catch (error) {
      console.error(error);
    }
  };

  const loadMoreData = async () => {
    try {
      const response = await fetch(API_URL);
      const jsonData = await response.json();
      setData([...data, ...jsonData]);
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <View>
      <FlatList
        data={data}
        renderItem={({ item }) => <Text>{item.name}</Text>}
        keyExtractor={(item) => item.id.toString()}
      />
      <Button title="Load more" onPress={loadMoreData} />
    </View>
  );
};

export default App;
英文:

In Homescreen, I am fetching data from json api and appending to data state variable. Each api call give 10 times. But the problem is, After 50 - 60 items app becomes very slow (even mobile freeze for 1-2 minutes). When I try to figure out the problem, and consoling each iterating of items, I seen the unnecessary re-renders while fetching to appending data to "setData" state. Look at the detailed problem below:

    import React, { useState, useEffect } from &#39;react&#39;;
import { View, Text, Button, FlatList } from &#39;react-native&#39;;

const API_URL = &#39;https://my-api-url.com/data&#39;;

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

  useEffect(() =&gt; {
    fetchData();
  }, []);

  const fetchData = async () =&gt; {
    try {
      const response = await fetch(API_URL);
      const jsonData = await response.json();
      setData(jsonData);
    } catch (error) {
      console.error(error);
    }
  };

  const loadMoreData = async () =&gt; {
    try {
      const response = await fetch(API_URL);
      const jsonData = await response.json();
      setData([...data, ...jsonData]);
    } catch (error) {
      console.error(error);
    }
  };

  return (
    &lt;View&gt;
      &lt;FlatList
        data={data}
        renderItem={({ item }) =&gt; &lt;Text&gt;{item.name}&lt;/Text&gt;}
        keyExtractor={(item) =&gt; item.id.toString()}
      /&gt;
      &lt;Button title=&quot;Load more&quot; onPress={loadMoreData} /&gt;
    &lt;/View&gt;
  );
};

export default App;

答案1

得分: 1

Sure, here's the translated code:

const App = () => {
  const [data, dispatchData] = useReducer((state, actionData) => ([...state, ...actionData]), []);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    try {
      const response = await fetch(API_URL);
      const jsonData = await response.json();
      dispatchData(jsonData);
    } catch (error) {
      console.error(error);
    }
  };

  const loadMoreData = async () => {
    try {
      const response = await fetch(API_URL);
      const jsonData = await response.json();
      dispatchData(jsonData);
    } catch (error) {
      console.error(error);
    }
  };

  const renderItem = useCallback(({ item }) => <Text>{item.name}</Text>, []);

  return (
    <View>
      <FlatList
        data={data}
        renderItem={renderItem}
        keyExtractor={(item) => item.id.toString()}
      />
      <Button title="Load more" onPress={loadMoreData} />
    </View>
  );
};

export default App;
英文:
const App = () =&gt; {
  const [data, dispatchData] = useReducer((state, actionData) =&gt; ([...state, ...actionData]), []);

  useEffect(() =&gt; {
    fetchData();
  }, []);

  const fetchData = async () =&gt; {
    try {
      const response = await fetch(API_URL);
      const jsonData = await response.json();
      dispatchData(jsonData);
    } catch (error) {
      console.error(error);
    }
  };

  const loadMoreData = async () =&gt; {
    try {
      const response = await fetch(API_URL);
      const jsonData = await response.json();
      dispatchData(jsonData);
    } catch (error) {
      console.error(error);
    }
  };

  const renderItem = useCallback(({ item }) =&gt; &lt;Text&gt;{item.name}&lt;/Text&gt;, []);

  return (
    &lt;View&gt;
      &lt;FlatList
        data={data}
        renderItem={renderItem}
        keyExtractor={(item) =&gt; item.id.toString()}
      /&gt;
      &lt;Button title=&quot;Load more&quot; onPress={loadMoreData} /&gt;
    &lt;/View&gt;
  );
};

export default App;

That should be enough.

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

发表评论

匿名网友

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

确定