用React过滤列表
嗯,我看不到我的遗漏,但是我得到了一个空白页面,显示控制台错误,内容为:
Users.js:9 Uncaught TypeError: Cannot read property 'filter' of undefined at Users.render (Users.js:9)
显然我使用了不正确的’filter()’。我环顾四周,但未发现与“反应”相关的任何内容。有人可以帮忙吗?这些是文件:
<!doctype html><html lang="en">
<head>
<meta charset="utf-8">
<title>React App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
index.js
import React from 'react';import ReactDOM from 'react-dom';
import Users from './Users';
ReactDOM.render(
<Users list={[
{ name: 'Tyler', friend: true },
{ name: 'Ryan', friend: true },
{ name: 'Michael', friend: false },
{ name: 'Mikenzie', friend: false },
{ name: 'Jessica', friend: true },
{ name: 'Dan', friend: false }
]}
/>,
document.getElementById('root')
);
Users.js
import React from 'react';class Users extends React.Component {
render() {
return (
<div>
<h1>Friends:</h1>
<ul>
{this.props.list.friend.filter(function (friend) {
return <li>{friend[0] === 'true'}</li>
})}
</ul>
<hr />
<h1>Non Friends:</h1>
<ul>
{this.props.list.friend.filter(function (nonFriend) {
return <li>{nonFriend[0] === 'false'}</li>
})}
</ul>
</div>
);
}
}
export default Users;
回答:
好的,看起来“ Users.js”应该是:
import React from 'react';class Users extends React.Component {
render() {
let friends = this.props.list.filter( function (user) {
return user.friend === true
});
let nonFriends = this.props.list.filter( function (user) {
return user.friend !== true
});
return (
<div>
<h1>Friends:</h1>
<ul>
{friends.map(function (user) {
return <li key={user.name}>{user.name}</li>
})}
</ul>
<h1>Non Friends:</h1>
<ul>
{nonFriends.map(function (user) {
return <li key={user.name}>{user.name}</li>
})}
</ul>
</div>
);
}
}
export default Users;
甚至这个:
import React from 'react';class Users extends React.Component {
render() {
return (
<div>
<h1>Friends:</h1>
<ul>
{this.props.list.filter(function (user) { // filter first for friends
return user.friend === true // returns a new array
}).map(function (user) { // map the new array to list items
return <li key={user.name}>{user.name}</li> // don't forget unique key for each item
})}
</ul>
<hr />
<h1>Non Friends:</h1>
<ul>
{this.props.list.filter(function (user) { // filter first for non-friends
return user.friend !== true // returns a new array
}).map(function (user) { //map the new array to list items
return <li key={user.name}>{user.name}</li> // don't forget unique key for each item
})}
</ul>
</div>
);
}
}
export default Users;
以上是 用React过滤列表 的全部内容, 来源链接: utcz.com/qa/410024.html