【问题标题】:React Native : make useState update on real timeReact Native:实时更新 useState
【发布时间】:2021-07-30 13:33:23
【问题描述】:

我在 react native 上有这段代码,每次按下按钮后我都会将计数器增加 1

     function App() {
          const [counter,setCounter]=useState(0);
          return (
            <View>
              <Button title="hello" onPress={()=> 
              {setCounter(counter+1);console.log("display 
               counter in console" ,counter)}}>
                </Button>

              {counter%2==1 ? <Text> display counter in UI</Text> 
               : null }
    
               <View>
               <Text> thank you for clicking the button </Text>
               </View>
        
            </View>
           )
             }

第一次单击后,计数器等于 0,控制台显示 0 而不是 1,因此 JSX 组件不会显示。 我知道 useState 是异步的,但是如果显示 JSX 取决于实时更新状态,如何解决它。

更新:JSX 似乎在预期时显示,但我想知道为什么 console.log 不会实时更新?我的意思是为什么 console.log 在应该显示 1 时显示 0

【问题讨论】:

  • 您需要同步更新做什么?单击按钮后,您的组件应立即以新状态重新渲染,但是 console.log 调用不会,因为它是在先前的渲染中调用的。
  • @Altareos 为什么console.log 不会实时更新?我的意思是,如果实际值为 1,为什么 console.log 显示 0 ?

标签: javascript reactjs react-native react-hooks


【解决方案1】:

您只需要在setCounter 状态上添加预增量运算符。并在 useState 声明中将 const 更改为 var。

https://snack.expo.dev/j70TThHHb

export default function App() {
              var [counter,setCounter]=useState(0);
              return (
                <View style={{marginTop:25}}>
                  <Button title="hello" onPress={()=> 
                  {setCounter(++counter);
                  console.log("display  counter in console" ,counter)}}>
                    </Button>
    
                  {counter%2==1 ? <Text> display counter in UI</Text> 
                   : null }
        
                   <View>
                   <Text> thank you for clicking the button </Text>
                   </View>
            
                </View>
               )
                 }

【讨论】:

【解决方案2】:

useState 钩子是异步的,所以你不能立即访问它的新值
而且它没有回调(不像setState
但是如果你想听它的变化,你可以像这样使用useEffect钩子

useEffect(() => {
    console.log('display  counter in console', counter);
}, [counter]);

【讨论】:

  • 我知道它是异步的,但实际上第一次点击时状态变为 1 但控制台显示 0 那么为什么它只对控制台异步?
  • @coldprogrammmer 因为异步函数在调用它们后不会立即完全执行。这意味着您的 console.logsetCounter 完全完成之前执行
猜你喜欢
  • 2021-11-15
  • 2021-01-07
  • 2022-08-14
  • 2021-03-06
  • 1970-01-01
  • 2020-12-30
  • 1970-01-01
  • 2021-05-27
  • 1970-01-01
相关资源
最近更新 更多