javascript - React Native中功能组件中构造函数的解决方案是什么?

标签 javascript reactjs react-native

让我带您解决我的问题。我正在制作一个计时器功能组件,我将 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/

相关文章:

javascript - 如何在 jQuery Submit() 执行之前运行代码?

ios - 如何在 iOS 启动时设置 Storyboard?

node.js - 创建新的 React Native 应用程序

react-native - React Native Navigation - 使用组件状态的 Action

javascript - JS 回调函数可以返回值吗?

javascript - Replit Discord 机器人不断关闭

javascript - html 模板中的更改不会反射(reflect)出来

reactjs - 如何找出哪个 React 组件抛出空 props 错误

javascript - 如何在最新版本 BabelJS 中启用对类属性的支持?

reactjs - GatsbyJS Build – 窗口未定义/模块未定义