如何在监听调整大小事件时设置我的状态一次

How can set my state once when listening resize event

在我的 React 应用程序中,我需要监听 window 的调整大小事件,因此如果 window 尺寸小于 X,我将调用 mobileFunc,如果它大于 X,我将调用调用 desktopFunc 来渲染一些 html 有很多变量。 (这些变量和参数为 desktopFunc 和 mobileFunc 获取不同的值)

我正在监听事件,但是,每次 window 的大小变化都会一次又一次地设置我的状态。我不想那样做。我正在尝试找到一种在必要时 set/change 我的状态的方法,并在可能的情况下减少侦听调整大小事件(可选)。我愿意接受有关去抖动、shouldComponentUpdate 等方面的建议。我应该找到一种有效的方法。

// mobile is false by default in my state.
componentDidMount() {
    window.addEventListener('resize', this.setDeviceType)
}
componentWillUnmount(){
    window.removeEventListener('resize', this.setDeviceType)
}

setDeviceType() {
    if(window.innerWidth < 768) {
        this.setState({mobile: true})
    } else {
        this.setState({mobile: false})
    }
}

render() {
    return(
        <div>
            {this.state.mobile ? this.mobileFunc() : this.desktopFunc()}
        </div>
    )
}

您可以使用去抖功能。 例如https://lodash.com/docs/#debounce

我没有测试过,但我认为这可能有效...

// mobile is false by default in my state.
componentDidMount() {
    window.addEventListener('resize', this.setDeviceType)
}
componentWillUnmount(){
    window.removeEventListener('resize', this.setDeviceType)
}

setDeviceType() {
    const { mobile } = this.state;
    if(window.innerWidth < 768) {
        if(!mobile) {
            this.setState({mobile: true})
        }
    } else {
        if(mobile) {
            this.setState({mobile: false})
        }
    }
}

render() {
    const { mobile } = this.state;
    return(
        <div>
            {mobile ? this.mobileFunc() : this.desktopFunc()}
        </div>
    )
}

if/else 块可以清理一些,但如果当前不是您想要的,您真的可以在线执行 setState