[英]React Native : make useState update on real time
I have this code on react native where I increment a counter by 1 after each button press我在 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>
)
}
After the first click the counter is equal to 0 and the console shows 0 instead of 1 so the JSX component won't show.第一次单击后,计数器等于 0,控制台显示 0 而不是 1,因此不会显示 JSX 组件。 I know that useState is asynchronous but how to solve it if showing a JSX is depending on updating the state on real time.
我知道 useState 是异步的,但是如果显示 JSX 取决于实时更新状态,如何解决它。
UPDATE: It seems that the JSX displays when excpected but I'm wondering why console.log will not update on real time ?更新:似乎 JSX 在 expected 时显示,但我想知道为什么 console.log 不会实时更新? I mean why console.log shows 0 when it is supposed to show 1
我的意思是为什么 console.log 在应该显示 1 时显示 0
You just need to add pre-increment operator on setCounter
state.您只需要在
setCounter
状态上添加预增量运算符。 and Change const to var in useState declaration.并将 useState 声明中的 const 更改为 var。
https://snack.expo.dev/j70TThHHb 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>
)
}
useState
hook is asynchronous, so you can not access it's new values immediately useState
钩子是异步的,所以你不能立即访问它的新值
And there is no callback for it (unlike setState
)并且没有回调(与
setState
不同)
But if you want to listen to it's changes, you can use useEffect
hook like this但是如果你想听它的变化,你可以像这样使用
useEffect
钩子
useEffect(() => {
console.log('display counter in console', counter);
}, [counter]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.