我是新来的本地人,现在我正在学习有关Hooks的基础知识。我创建了一个名为Timer的非常简单的组件,它具有三个按钮-启动,停止和手动更改计数器。计数器是一个useState挂钩。 现在的问题是:当我通过从按钮调用changeCounterHandler函数来更改计数器时,一切正确。当我启动计时器时,我看到它正在“滴答”,但计数器从未更改,并且组件未重新渲染。为什么? :-)
import React, { useState, useEffect, useRef } from 'react';
import { StyleSheet, View, Button, Text } from 'react-native';
const Timer = props => {
const [counter, setCounter] = useState(0);
const timerId = useRef();
const timerDidMount = () => {
console.log("timerDidMount");
};
const changeCounterHandler = () => {
setCounter(counter+1);
console.log(`counter: ${counter}`);
};
const startTimer = () => {
timerId.current = setInterval(changeCounterHandler,1000);
};
const stopTimer = () => {
clearInterval(timerId.current);
};
return (
<View>
<Text>{counter}</Text>
<Button title="Start timer" onPress={startTimer}></Button>
<Button title="Stop timer" onPress={stopTimer}></Button>
<Button title="change counter" onPress={changeCounterHandler}></Button>
</View>
)
};
const styles = StyleSheet.create({
});
export default Timer;
谢谢 扬
答案 0 :(得分:0)
查看是否可行:使用函数格式设置setCounter: setCounter(counter => counter + 1);