【问题标题】:Why would my property be undefined on state in React?为什么我的属性在 React 中的状态上未定义?
【发布时间】:2018-03-15 13:41:11
【问题描述】:

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

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

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

【问题讨论】:

  • 您的意思可能是const { isLoading } = this.state。您当前的代码正在寻找不存在的this.state.isLoading.isLoading
  • const {isLoading} = this.state
  • 要么删除 {} 并使用 const isLoading = this.state.isLoading 要么 使用这个:const {isLoading} = this.state

标签: javascript reactjs react-native


【解决方案1】:

问题在于您的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}/>);
    }

【讨论】:

    【解决方案2】:

    isLoading 实际上并不存在,你可能会这样写:

    if (this.state.isLoading)
    

    但你也可以通过这样做来解构对象

    const {isLoading} = this.state
    

    然后:

    if(isLoading)
    

    【讨论】:

      【解决方案3】:

      这样使用const {isLoading} = this.state 这样你把 isLoading 的 isLoading 放在 cont 变量中是未定义的

      【讨论】:

        【解决方案4】:
        > const {isLoading} = this.state;
        

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-04-07
          • 1970-01-01
          • 2021-09-13
          • 2021-09-12
          • 1970-01-01
          • 2019-12-15
          • 1970-01-01
          • 2022-11-30
          相关资源
          最近更新 更多