簡體   English   中英

為什么 console.logs 與中呈現的 output 不匹配<text>在這個基本的 React Native Expo 項目中的表達式</text>

[英]Why does console.logs does not matched the output rendered in <Text> expression in this basic React Native Expo Project

我在更新計數之前和之后都嘗試過控制台日志,它正在屏幕上更新值,而不是在我用來驗證結果的控制台日志中更新值。

import { StyleSheet, Text, View, Button } from "react-native";
import React from "react";
import { useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);

  const increaseCount = () => {
    console.log(`Count initially -- ${count}`);
    setCount(count + 1);
    console.log(`Count finally -- ${count}`);
  };

  return (
    <View style={styles.container}>
      <Button title="Change Value" onPress={increaseCount} />
      <Text>{count}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
});

請報告我正在做的任何錯誤或背后的原因。

我嘗試添加設置超時來代替控制台日志,因為我認為它們可能需要一些時間才能更新,但輸出是相同的,它不起作用。

已編輯 ------

但是如果 useState 是 async function 並且我現在嘗試在調用 setCount 時使 increaseCount function async 和 await,根據我的理解它現在應該可以工作但是它沒有 ☹️。 我要問的是,我目前正在學習 useState,在我可能需要在下一行代碼中使用更新值的更大程序中,我怎么能信任 useState,而我什至無法預測它何時會更新我的state。

import { StyleSheet, Text, View, Button } from "react-native";
import React from "react";
import { useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);

  const increaseCount = async () => {
    console.log(`Count initially -- ${count}`);
    await setCount(count + 1);
    console.log(`Count finally -- ${count}`);
  };

  return (
    <View style={styles.container}>
      <Button title="Change Value" onPress={increaseCount} />
      <Text>{count}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
});

你已經很接近答案了,React Native setState 是異步的 function。所以它不會立即更新值。

如果要使用更新后的值,請使用useEffect()

export default function App() {

  const [count, setCount] = useState(0);

  React.useEffect(() => {
    //When count is changed, this function is triggered with updated value
    console.log(`Count finally -- ${count}`);
  }, [count]);

  const increaseCount = () => {
    console.log(`Count initially -- ${count}`);
    setCount(count + 1);
  };

  return (
    <View style={styles.container}>
      <Button title="Change Value" onPress={increaseCount} />
      <Text>{count}</Text>
    </View>
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM