繁体   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