我从Local API服务器中获取了发送JSON数据的用户数据,并且在添加搜索功能之前起作用。我认识到这些错误是从React的生命周期样式发生的,但是由于我没有研究React太多,所以我要问问题以解决您的问题。
macos mojave,express.js,react.js和react-router正在运行我的本地开发服务器。我以前从未尝试过此搜索功能。
这些是我的代码:
userlist.js:
import React, {Component} from 'react';
import {List, Avatar, Button, Modal, Input} from 'antd';
import UserItem from "../components/UserItem";
import blue_check from '...';
const {Search} = Input;
class UsersList extends Component {
state = {
users: [],
modalVisible: false,
dataKey: 0,
keyword: '',
};
constructor(props) {
super(props);
this.state = {
users: [{
member_idx: 0,
nickname: 'loading...',
}]
};
}
componentDidMount() {
fetch('/api/getUsers')
.then(res => res.json())
.then(users => this.setState({users: users}));
}
showModal = (key) => {
this.setState({
modalVisible: true,
dataKey: key
});
};
handleClose = e => {
console.log(e);
this.setState({
modalVisible: false
});
};
handleSearch = (e) => {
this.setState({
keyword: e.target.value,
})
};
render() {
const {users, keyword} = this.state;
const filteredUsers = users.filter(
user => user.nickname.indexOf(keyword) !== -1
); // This line makes error
return (
<div>
<Search
placeholder="Input Search Text"
enterButton="Search"
onSearch={value => this.state.handleSearch(value)}
size="large"
/>
<List
itemLayout="horizontal"
dataSource={filteredUsers}
renderItem={item => (
<List.Item
actions={[<a onClick={() => this.showModal(item.member_idx)}>상세정보</a>, <a>이 프로필을...</a>]}>
<List.Item.Meta
style={{
display: 'flex',
alignItems: 'center'
}}
avatar={<Avatar src={item.image}/>}
title={
<span>{item.nickname === null ? "<undefined>" : item.nickname} {item.blue_check === 1 &&
<img src={blue_check} alt="BLUE" style={{height: '16px'}}/>
}</span>}
description={
<span><strong>{item.follow_count}</strong> Follower{item.follow_count !== 1 && "s"}</span>}
/>
</List.Item>
)}
/>
<Modal
title="상세 정보"
visible={this.state.modalVisible}
onClose={this.handleClose}
footer={[
<Button key="back" onClick={this.handleClose}>
닫기
</Button>
]}
centered
>
<UserItem dataKey={this.state.dataKey} users={this.state.users}/>
</Modal>
</div>
);
}
}
export default UsersList;
userItem.js在这篇文章中不需要,因为此错误没有问题。
我在此处链接了错误跟踪图像。对不起。
在您的数据中,nickname
在一个或多个用户中可能是无效的,因此您在过滤时也应该对其进行检查
const filteredUsers = users.filter(
user => user.nickname && user.nickname.indexOf(keyword) !== -1
);