【问题标题】:Functional component to class component Error: Cannot read property 'id' of undefined功能组件到类组件错误:无法读取未定义的属性“id”
【发布时间】:2020-12-25 21:25:39
【问题描述】:

我正在处理一个小项目,并且正在将功能组件转换为基于类的组件,以便我的组件可以管理其状态。在翻译组件时,我遇到了一个错误:

TypeError:Cannot read property 'id' of undefined

此组件用作功能组件,因此我不确定为什么我现在收到此错误。谁能回答为什么在从功能组件转换为基于类的组件时我收到此错误?这与范围有关吗?我只是有一些语法错误吗?我一直在努力解决这个问题,只是不明白为什么它无法读取现在在我的组件渲染部分返回中的“id”属性。

组件代码:

  import React, {Component} from "react";
import "./OpenTasksComponent.css"



class openTasks extends Component{
  constructor(){
      super();

    this.handleClick = this.handleClick.bind(this);
  }

     handleClick(){
        let x = document.body.nodeName;
        console.log(x);
    }
    
    render(){

        return (
    
            <div className="tasks" value = {this.task.id}>
                <h1 onClick={this.handleClick}>{this.task.clientName}</h1>
                <div className="accordion-item accordion-item-open">
                    <h2>{this.task.matter}</h2>
                    <p>{this.task.matterStatus}</p>
                </div>
            </div>
        )

    }
    
    
}

export default openTasks

应用代码:

import './App.css';
import Task from './components/open-tasks-component/open-tasks-component';
import tasksData from './components/open-tasks-component/tasks-data';
import Header from './Header';

function App() {
  const Tasks = tasksData.map(task=> <Task key={task.id} task ={task}/>)
  return (
    <div className="App">
        <Header />
    
        {Tasks}
    </div>
  );
}

export default App;

【问题讨论】:

  • 你要使用this.props.task
  • 在你的功能组件中使用 useState 钩子? reactjs.org/docs/hooks-state.html
  • @Will 我还不知道如何使用钩子。仍在学习 React 的基础知识,我正在研究基于类的组件,但我很欣赏这是解决为功能组件提供一种管理状态的方法的另一种方法。

标签: javascript reactjs


【解决方案1】:

在 App 中,您向下传递了一个 prop,但您尝试使用 this.task.id 在子类组件中读取它,它应该是 this.props.task.id

【讨论】:

  • 谢谢拉希德。这行得通。你能解释一下为什么在从功能组件转移到基于类的组件时这是必要的吗?我之前不是传过道具吗?
  • 不用担心,我不确定你的组件以前是什么样子的,但你可能有 "functionComponent({prop1,prop2})" 破坏语法,你可以在你的课堂上做同样的事情渲染中的组件类似于“const {prop1, prop 2} = this.props”
  • 基本上我在 return 语句中拥有一切,只是没有 handleClick() 方法,也没有构造函数。然而,它适用于 this.task.id
【解决方案2】:

功能组件也可以管理状态。 你可以使用 useState。

const [state, setState] = useState(null);

【讨论】:

  • 我明白,但我还没有进阶到学习钩子。我目前正在使用没有钩子的基于类的功能组件。一旦我学会了钩子,我相信我会开始实现它们。
猜你喜欢
  • 1970-01-01
  • 2017-05-12
  • 1970-01-01
  • 2021-11-24
  • 2020-01-27
  • 1970-01-01
  • 2021-07-05
  • 1970-01-01
  • 2020-10-29
相关资源
最近更新 更多