我正在这里编写一个示例应用程序来了解 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;
最佳答案
您在 ContactListItem#render()
中收到错误因为Link
未定义。从 React Router v4 开始,<Link />
不再是 react-router
的一部分,而是 react-router-dom
的一部分包裹。更改此设置应该可以解决您的问题:
import { Link } from 'react-router-dom';
关于javascript - 我这里的 render 方法有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45736801/