javascript - 我这里的 render 方法有什么问题?

标签 javascript reactjs

我正在这里编写一个示例应用程序来了解 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/

相关文章:

javascript - 没有小时、分钟和秒的 getTime 对应的日期是什么?

css - 有没有办法在不使用 className 的情况下使用 ID 为 React 中的元素设置样式?

css - 如何在 React Native 中使用 Flex 居中组件?

javascript - 将项目数据从 JSON 文件动态加载到 React 中

reactjs - waitFor 不等待回调被调用

javascript - 在 ES6 React .JS 中使用 Async/Await

javascript - 如何将 select2 4.0 与 angularjs 一起使用,何时初始化它

Javascript:如何检查样式是否已注入(inject)

javascript - YouTube API - iframe onStateChange 事件

javascript - jQuery 触发事件后停止事件传播