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的新手,所以我遇到了这个问题。我意识到这个问题已被提出,我仔细查看了所有这些问题,但仍然无法找到解决方案,因为我收到了这个错误。我想根据employees
过滤数组searchValue
并显示更新Employee Table
。
答案 0 :(得分:2)
正如错误消息告诉您的那样,问题是您的常量employees
未定义。问题出在您正在渲染HeaderSearch
组件的位置。很可能你没有传递你认为你的道具。尝试渲染<HeaderSearch employees={[]} />
。它有用吗? console.log(this.props)
向您展示了什么?你能看到关键employees
吗?
如果您需要更多帮助,请将代码发布到实际呈现HeaderSearch
组件的位置。
答案 1 :(得分:1)
只需添加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或未定义,当您提供默认值为空数组时,Array.filter
不会抛出错误,因为默认值为{{ 1}}是Array