Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React Native:HOC在使用`onLayout'时缺少状态`_Javascript_Reactjs_React Native - Fatal编程技术网

Javascript React Native:HOC在使用`onLayout'时缺少状态`

Javascript React Native:HOC在使用`onLayout'时缺少状态`,javascript,reactjs,react-native,Javascript,Reactjs,React Native,此组件呈现占位符&一旦获得布局,此HOC将更新状态并使用值调用子级 到目前为止一切正常,但当子级调整大小(WillChangeSizeIn3Seconds)时,会再次调用render,但这次的状态是{} 当它第二次调用render时,实际上就在组件卸载调用之前 为什么状态在重新渲染时不保持 // HOC const onLayout = Placeholder => class OnLayout extends Component { state = {}

此组件呈现
占位符
&一旦获得布局,此HOC将更新状态并使用值调用子级

到目前为止一切正常,但当子级调整大小(
WillChangeSizeIn3Seconds
)时,会再次调用render,但这次的状态是
{}

当它第二次调用
render
时,实际上就在
组件卸载调用之前

为什么状态在重新渲染时不保持

// 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
const onLayout=占位符=>
类OnLayout扩展了组件{
状态={}
组件将卸载(){
调试器
}
componentDidMount(){
调试器
}
onLayout=({nativeEvent:{layout}})=>{
this.setState({layout})
}
render(){
const{children,…rest}=this.props
const{layout}=this.state
返回布局(
儿童(布局)
) : (
)
}
}
//用法
类TestComponent扩展组件{
render(){
const OnLayout=OnLayout(加载)
返回(
({(宽度、高度)})=>{''}
)
}
}

问题在于,HOC应用程序位于render方法中,这意味着
OnLayout
TestComponent
的每个重新渲染器上都是不同的类。这反过来会导致先前的
OnLayout
被卸载并替换为新的,从而丢失所有状态


在HOCs上的React文档中可以找到更多信息:

定义了
const OnLayout=OnLayout(Loading)
的确切位置?它是在另一个组件中定义的……如果它是在
render
方法中定义的,请将其移动到模块的顶层,因为这可能解释了rerender上的状态丢失。哇,就这样,非常感谢!想回答这个问题,这样我就可以把它标记为例外答案了?