在上下文API中,可以在componentDidMount中定义使用者吗?

时间:2018-08-21 06:20:55

标签: reactjs react-context

在上下文状态下,我有一个HandlePopUp函数和一个Visibility布尔值。在构造函数中,我将Visibility = false和HandlePopUp设置为以下内容。

HandlePopUp: () => {
    //toggles Visibility to true and false. by default its set to false.
}

在另一个组件中,我试图像这样使用使用者:

export class OwnersHeader extends React.Component {
    private localContext;
    public componentDidMount() {
        return <MyConsumer>
                    {(context) => {
                        return (
                            this.localContext = context
                        );
                    }}
                </MyConsumer>;
    }

    public render() {
        return (
            <div>
                <button onClick={this.localContext.HandlePopUp}>Open PopUp</button>
                { this.localContext.Visibility ? <PopUp /> : null }
            </div>
        );
    }
}

我试图将上下文加载到局部变量中,然后使用它有条件地呈现PopUp组件。但这会引发Cannot read property 'HandlePopUp' of undefined错误。

给我留下了深刻的印象,将上下文存储在componentDidMount(在渲染之前触发)将允许我执行此操作。

我该如何解决?谢谢!

0 个答案:

没有答案