首页 > 解决方案 > 如何在 React 组件中使用对象数据

问题描述

我试图制作一个粘性应用程序,为此我编写了两个组件。一个是容器,它渲染其中的每个粘性组件,第二个使用从 JSON 提供给它的数据。

class App extends React.Component {
  state = {
    notes: tasks
  }

  render(){
    return <Stickycontainer tasks={this.state.notes}/>
  }
}

class Stickycontainer extends React.Component{
  render(){
    return this.props.tasks.map(e => <Stickynote data={e}/>)
  }
}

这个片段工作得很好,因为我尝试而不是渲染一个 Stickynote,而是只渲染一个带有每个对象及其数组属性的段落元素。但是当我尝试在下面实现 Sticky 组件时出现错误:

class Stickynote extends React.Component{
    state = {
      show: true
    }

    render(){
      if(this.state.show){
        return(
          <div className="StickyNotes">
            <p>{this.props.data.id} - {this.props.data.description} - {this.props.data.title}</p>
    
            <div className="Actions">
              <button className="Delete" onClick={() => this.setState({show: false})}>
                  <Icon>delete</Icon>
              </button>
    
            </div>
          </div>
        );
      } else {
        return null;
      }
        
    } 
  }

它给了我这个错误:

错误:元素类型无效:需要字符串(对于内置组件)或类/函数(对于复合组件),但得到:对象。

检查渲染方法App

我该怎么办?

标签: javascriptreactjsjson

解决方案


推荐阅读