让我带您解决我的问题。我正在制作一个计时器功能组件,我将 startValue 传递给组件,然后该组件将使用通过 Prop 传递的 startValue 启动计时器(每秒减少一秒)。
const FunctionalComponent = (props: any) => {
const [timerValue, setTimerValue] = useState(props.initialValue)
console.log('Set State')
useEffect(() => {
console.log('UseEffects called')
setInterval(() => {
setTimerValue(timerValue - 1)
}, 1000)
}, [])
return <View><Text style={styles.textStyle}>{timerValue}</Text></View>
我在 Parent 中的渲染函数。
render() {
return <View style={styles.mainView}>
<FunctionalComponent initialValue={30} />
</View>
}
现在,每次重新渲染父组件时,都会调用 FunctionalComponent 并重置 timerValue 值。我使用类组件构造函数解决了这个问题,但我想知道是否有任何解决方案可以在功能组件中执行相同的操作。
class OTPTimer extends Component {
constructor(props: any) {
super(props)
this.state = {
timeLeft: props.fromStart
}
if (props.startTimer) {
this.startTimer()
}
}
componentDidUpdate(prevProps: any) {
if (!prevProps.startTimer && this.props.startTimer) {
this.startTimer()
this.setState({
timeLeft: this.props.fromStart
})
}
}
startTimer = () => {
var interval = setInterval(() => {
this.setState({
timeLeft: this.state.timeLeft - 1
})
if (this.state.timeLeft === 0) {
clearInterval(interval)
}
}, 1000)
}
render() {
return <Text style={globalStyles.testStyleThree}>{`00:${this.state.timeLeft > 9 ? this.state.timeLeft : `0${this.state.timeLeft}`}`}</Text>
}
}
最佳答案
结帐React.memo , 如果 props 没有改变,女巫将阻止子组件重新渲染
const FunctionalComponent = React.memo((props: any) => { .... } )
关于javascript - React Native中功能组件中构造函数的解决方案是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62860528/