2016-04-30 120 views
5

我是React的新手,嘗試通過屬性傳遞對象,但獲得跟隨錯誤。React - 通過道具傳遞對象

Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {title}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of MeetingComponent. 

這裏是我的代碼:

Main.jsx

import React from 'react'; 
import MeetingComponent from '../components/Meeting.jsx'; 

let meeting = { 
    title: 'Some title' 
}; 

class AppComponent extends React.Component { 
    render() { 
     return (
      <div className="index"> 
       <MeetingComponent dataMeeting={meeting} /> 
      </div> 
    ); 
    } 
} 

AppComponent.defaultProps = {}; 

export default AppComponent; 

Meeting.jsx

import React from 'react'; 

class MeetingComponent extends React.Component { 
    render() { 
     return (
      <div>{this.props.dataMeeting}</div> 
     ); 
    } 
} 

MeetingComponent.defaultProps = {}; 

export default MeetingComponent; 

我該如何解決這個問題?最佳做法是什麼?

回答

9

的問題是在這裏

<div>{this.props.dataMeeting}</div> 

不能渲染對象的反應,也許你試圖做

<div>{this.props.dataMeeting.title}</div> 
-6

最好的做法是讓你的道具爲純越好,你的情況它可能是

<MeetingComponent title={ meeting.title } /> 

class MeetingComponent extends React.Component { 
propTypes = { 
    title: React.PropTypes.string.isRequired 
} 
render() { 
    return (
     <div>title: { this.props.title }</div> 
    ); 
    } 
} 

而且總是用propTypes更好的警告消息