首页 > 解决方案 > 在本机反应中抵消一

问题描述

我在 react-native 中有一个使用 useState 的计数器增量器。每当我按下一个按钮时,计数应该加一。它工作正常,但是当第一次按下时,计数器仍然为 0,当第二次按下时,计数器增加 1 并顺利继续,没有问题。为什么第一版不更新?这是代码:

import { StatusBar } from 'expo-status-bar';
import React, {useState } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';

export default function App() {
  
  const [count, setCount] = useState(0);
  const [outputState, setOutputState] = useState(`You have tapped ${count} times`);

  const getFinalResult = () => {
    setCount(count => count + 1);
    setOutputState(`You have tapped ${count} times`);
    
  }
  return (
    <View style={styles.container}>
      <Text>{outputState}</Text>
      <Button title="change text" onPress={getFinalResult} />
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

标签: reactjsreact-nativereact-hooksuse-state

解决方案


此代码将为您工作。您正在同时设置状态和显示。设置状态是异步任务,需要一些时间才能完成。

import { StatusBar } from 'expo-status-bar';
import React, {useState } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';

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

  return (
    <View style={styles.container}>
      <Text>You have tapped {count} times</Text>
      <Button title="change text" onPress={() => setCount(count => count + 1)} />
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});


推荐阅读