如何在React Native中避免重新初始化useState变量

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

How to avoid reinitializing a useState variable in React Native

问题

I am working on a music app in React Native. This page will be re-opened several times, but I do not want the trackList to reset to [] every time the page is re-rendered, but instead to retain its values. I have included a simplified version of my code:

let existsTrackListener = false;

export default function Host({ navigation }) {
  const [trackList, setTrackList] = useState([]);

  if (!existsTrackListener) {
    setTrackListener(roomID, (t) => {
      if (t != null) {
        const newArray = [...trackList, t.name];
        setTrackList(newArray);
      }
    });
    existsTrackListener = true;
  }

  return (
    <View style={styles.container}>
      <FlatList
        data={trackList}
        renderItem={({ item }) => <Text style={styles.item}>{item}</Text>}
      />
    </View>
  );
}

(Note: I retained the code as-is and provided the translation in your requested format.)

英文:

I am working on a music app in React Native. This page will be re-opened several times, but I do not want the trackList to reset to [] everything the page is re-rendered, but instead to retain its values. I have included a simplified version of my code:

let existsTrackListener = false;

export default function Host({ navigation }) {
  const [trackList, setTrackList] = useState([]);

  if (!existsTrackListener) {
    setTrackListener(roomID, (t) =&gt; {
      if (t != null) {
        const newArray = [...trackList, t.name];
        setTrackList(newArray);
      }
    });
    existsTrackListener = true;
  }

  return (
    &lt;View style={styles.container}&gt;
      &lt;FlatList
        data={trackList}
        renderItem={({ item }) =&gt; &lt;Text style={styles.item}&gt;{item}&lt;/Text&gt;}
      /&gt;
    &lt;/View&gt;
  );
}

答案1

得分: 2

如果你希望在应用程序运行时保持状态,你可以使用React上下文

如果你希望将状态持久化存储,以便在下次启动应用程序时可用,考虑使用数据库。有许多可用的数据库,例如SQLite、Realm、Firebase(云选项)。

英文:

If you want the state to live while the app is running, you can can use react context.

If you want to persist the state on storage so it's available on the next launch of your app, consider using database. There are many databases available, such as SQLite, Realm, Firebase (cloud option).

huangapple
  • 本文由 发表于 2023年5月15日 12:44:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76250930.html
匿名

发表评论

匿名网友

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

确定