簡體   English   中英

React Native:使用`onLayout`時HOC Missing狀態

[英]React Native: HOC Missing state when using `onLayout`

此組件呈現Placeholder ,並且一旦獲得布局,此HOC就會更新狀態並使用值調用子級。

到目前為止一切都很好,但是當子級調整大小( WillChangeSizeIn3Seconds )時,再次調用render,但這一次狀態為{}

當它第二次調用render時,它實際上恰好在componentWillUnmount調用之前。

為什么國家在重新渲染時不持久?

// HOC

const onLayout = Placeholder =>
    class OnLayout extends Component {
        state = {}

        componentWillUnmount() {
            debugger
        }

        componentDidMount() {
            debugger
        }

        onLayout = ({ nativeEvent: { layout } }) => {
            this.setState({ layout })
        }

        render() {
            const { children, ...rest } = this.props
            const { layout } = this.state

            return layout ? (
                children(layout)
            ) : (
                <Placeholder {...rest} onLayout={this.onLayout} />
            )
        }
    }

// Usage

class TestComponent extends Component {
    render() {
        const OnLayout = onLayout(Loading)

        return (
            <View>
                <OnLayout>
                    ({(width, height)}) =>{' '}
                    <WillChangeSizeIn3Seconds width={width} height={height} />
                </OnLayout>
            </View>
        )
    }
}

問題在於HOC應用程序位於render方法內部,這意味着OnLayout將在每次TestComponent渲染時成為不同的類。 反過來,這將導致先前的OnLayout被卸載並被新的OnLayout取代,從而丟失所有狀態。

在HOC的React文檔中可以找到更多信息: 不要在render方法內使用HOC。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM