繁体   English   中英

为什么我的属性在React中的状态上未定义?

[英]Why would my property be undefined on state in React?

我的属性isLoading是一个布尔型状态,我检查该状态以确定渲染代码的主体是否已准备好执行或应与正在旋转的加载程序一起等待。 当我在调试器中检查状态时,isLoading是一个布尔值,但是当我进一步检查isLoading时,它是未定义的。 而且这是在同一断点之内(除了将鼠标悬停在1秒之外的其他属性上,我什么也没做)。 这真的搞砸了我的代码,因为isLoading属性随后在其下面的if语句中是未定义的,因此它不会等待我的代码准备就绪。 谁能告诉我为什么我的isLoading属性是不确定的,即使当我查看状态为布尔值时也是如此?

    render() {
    const {isLoading} = this.state.isLoading;

    if (isLoading) {
        return (<Loader isVisible={true}/>);
    }

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

isLoading实际上并不存在,您可能会这样说:

if (this.state.isLoading)

但您也可以通过以下方式进行对象解构

const {isLoading} = this.state

然后:

if(isLoading)

问题出在你的const {isLoading} = this.state.isLoading;

它必须是const {isLoading} = this.state;

因为根据您的代码const {isLoading} = this.state.isLoading; 意味着this.state.isLoading.isLoading希望返回一个未定义的值

这应该工作正常

 render() {
    const {isLoading} = this.state;

    if (isLoading) {
        return (<Loader isVisible={true}/>);
    }

以这种方式使用它const {isLoading} = this.state表示将isLoading的isLoading放入cont变量中的方式未定义

> const {isLoading} = this.state;

这应该是语法。 以上内容称为解构,并在ES6中引入。 在以上语法中,从组件状态为变量分配了isLoading的值。

您要尝试执行的操作将在this.state.isLoading搜索另一个this.state.isLoading

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM