开发者问题收集

未捕获的类型错误:无法读取未定义的属性“过滤器”

2017-08-14
16476
import React, {PureComponent} from 'react';
import {TextInput} from '../../shared';
import {array} from 'prop-types';
import { EmployeeTable } from '../employeeTable/EmployeeTable';
import './HeaderSearch.scss';

export class HeaderSearch extends PureComponent {
    static propTypes = {
        employees: array
    }

    constructor (props) {
        super(props);

        this.state = {
            searchValue: null
        };
    }

    _updateSearchValue (value) {
        this.setState({
            searchValue: value
        });
    }

    render () {
        const employees = this.props.employees;
        let filteredEmployees = employees.filter(
                (employee) => {
                    return employee.name.indexOf(this.state.searchValue) !== -1;
                }
            );
        return (
            <div className='header_search'>
                <ul>
                    {filteredEmployees.map((employee) => {
                        return <EmployeeTable
                            employees={employee}
                            key={employee.id}
                            />;
                    })}
                </ul>
                <TextInput
                    label='Search for people'
                    value={this.state.searchValue}
                    onChange={(e) => this._updateSearchValue(e.target.value)}
                    />
            </div>
        );
    }
}
export default HeaderSearch;

我是 ReactJS 的新手,所以我被这个问题难住了。我意识到这个问题已经被问过了,我查看了所有问题,但仍然找不到解决我为什么会收到此错误的解决方案。我想根据 searchValue 过滤数组 employees 并显示更新的 Employee Table

2个回答

只需为 HeaderSearch 添加默认值即可

import React, {PureComponent} from 'react';
import {TextInput} from '../../shared';
import {array} from 'prop-types';
import { EmployeeTable } from '../employeeTable/EmployeeTable';
import './HeaderSearch.scss';

export class HeaderSearch extends PureComponent {

    static defaultProps = { // <-- DEFAULT PROPS
        employees: []       // undefined gets converted to array,render won't trigger error
    }

    static propTypes = {
        employees: array
    }

    constructor (props) {
        super(props);

        this.state = {
            searchValue: null
        };
    }

    _updateSearchValue (value) {
        this.setState({
            searchValue: value
        });
    }

    render () {
        // omitted
    }
}
export default HeaderSearch;

当未提供 employees prop 或为 null 或 undefined 时会触发错误,当您提供空数组的默认值时, Array.filter 不会抛出错误,因为 employees 的默认值是数组的一个实例

Medet Tleukabiluly
2017-08-14

正如错误消息所告诉您的,问题在于您的常量 employees 未定义。问题将出现在您呈现 HeaderSearch 组件的地方。很可能您没有将您认为的 props 传递给它。尝试呈现 <HeaderSearch employees={[]} /> 。它有效吗? console.log(this.props) 向您显示了什么?您能在那里看到关键的 employees 吗?

如果您需要更多帮助,请发布您实际呈现 HeaderSearch 组件的代码。

Marek Takac
2017-08-14