2017-08-17 85 views
1

我在這裏寫了一個示例應用程序來讓我的頭在React中,但我的一個簡單組件拋出一個我似乎無法跟蹤的錯誤。我的渲​​染方法在這裏有什麼問題?

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of ContactListItem .

下面是ContactListItem組件的代碼。

import React, { Component } from 'react'; 
import { ListGroupItem } from 'react-bootstrap'; 
import { Link } from 'react-router'; 

class ContactListItem extends Component { 
    render() { 
     const { contact } = this.props; 
     return (
      <ListGroupItem> 
       <Link to={'/contact/${contact.id'}> 
        <h4>{contact.name}</h4> 
       </Link> 
      </ListGroupItem> 
     ); 
    } 
} 

export default ContactListItem; 

這是一個非常簡單的類。沒有任何東西可以成爲問題。爲了完成,這裏是父組件。

import React, { Component } from 'react'; 
import { ListGroup } from 'react-bootstrap'; 
import ContactActions from '../actions/ContactActions'; 
import ContactStore from '../stores/ContactStore'; 
import ContactListItem from './ContactListItem'; 

function getContactListItem(contact) { 
    return (
     <ContactListItem key={contact.id} contact={contact} /> 
    ); 
} 

class ContactsComponent extends Component { 
    constructor() { 
     super(); 
     this.state = { 
      contacts: [] 
     } 
     this.onChange = this.onChange.bind(this); 
    } 

    componentWillMount() { 
     ContactStore.addChangeListener(this.onChange); 
    } 

    componentDidMount() { 
     ContactActions.receiveContacts() 
    } 

    componentWillUnmount() { 
     ContactStore.removeChangeListener(this.onChange); 
    } 

    onChange() { 
     this.setState({ 
      contacts: ContactStore.getContacts() 
     }); 
    } 

    render() { 
     let contactListItems; 

     if (this.state.contacts) { 
      contactListItems = this.state.contacts.map(contact => getContactListItem(contact)); 
     } 
     return (
      <div> 
       <ListGroup> 
        {contactListItems} 
       </ListGroup> 
      </div> 
     ); 
    } 
} 

export default ContactsComponent; 
+0

您是否嘗試過使用非空'contacts'數組? – Mahdi

回答

3

你得到的錯誤ContactListItem#render()因爲Link是不確定的。截至React Router v4,<Link />不再是react-router的一部分,而是react-router-dom包的一部分。改變這應該解決您的問題:

import { Link } from 'react-router-dom'; 
+1

這確實解決了它。謝謝! React-Router在發佈這些教程之間改變了方式,現在正在讓我失望。每當我碰到這樣的路障時,它總是相同的答案「React路由器不再像那樣工作了」。謝謝你清理那個。 –

1

documentation, 使用

import { Link } from 'react-router-dom';` 

不像react-router其用於早期的工作。

但是,react-router-dom隨附:

  • HashRouter

  • BrowserRouter

  • MemoryRouter

  • 提示

  • NavLink

  • StaticRouter等

你可能會從樹搖晃了很多,受益於使用

import Link from 'react-router-dom/Link'; 

如果您的應用程序並不需要上述所有的東西。