我有一个 React 应用程序,可以过滤用户和帖子。我的导航栏可以链接到用户、帖子。
点击帖子会显示所有用户发布的每一篇帖子的列表(每个帖子都有一些额外的元信息)。
这是我的帖子组件:
export default class Posts extends Component {
render() {
return (
<div>
{this.props.posts.map( post =>
<Post {...this.props} post={post} key={post.id} />
)}
</div>
)
}
}
在用户页面上,每个用户都有一个子链接帖子。我想要的是能够单击该用户的帖子,并将您带到帖子页面(如上所示),但仅列出该用户的帖子。
posts 数组看起来有点像这样:
[
{ id: 1,
userId: 1
},
{ id: 2,
userId: 1
},
{ id: 3,
userId: 2
},
{ id: 4,
userId: 3
},
{ id: 5,
userId: 3
}
]
假设我点击了 userId
为 3
的用户,并且只想显示他/她的帖子。做这个的最好方式是什么?
我知道我可以使用react-router将userId
传递给URL,然后将其拉回到组件中,但我不确定一旦Posts组件呈现如何使用它。最终我希望它渲染过滤到 userId 路由参数的 posts 数组,否则渲染所有帖子。这是正确的方法吗?
感谢任何帮助。
<小时/>更新:
好吧,我知道这不是一个优雅的解决方案,但我想从一个解决方案开始,然后我会“trim 它”,可以这么说。
这段代码中有一个我无法弄清楚的错误:
render() {
const {userId} = this.props.params
if(userId) {
const postsForUser = posts.filter( post => post.userId === userId )
return (
<div>
{postsForUser.map( post =>
<Post {...this.props} post={post} key={post.id} />
)}
</div>
)
}
else {
return (
<div>
{this.props.posts.map( post =>
<Post {...this.props} post={post} key={post.id} />
)}
</div>
)
}
} // end render()
当我记录 userId
时,它会正确记录我刚刚单击的用户 ID,因此我的 this.props.params.userId
变量工作正常。
如果我使用硬编码整数定义 postsForUser
,例如
const postsForUser = posts.filter( post => post.userId === 3 )
它正确返回过滤后的数组。
所以现在看来一切都工作正常,除了当我交换变量的硬编码 id 时,postsForUser
返回一个空数组。
我哪里出错了?
<小时/>更新 2(修复):
对于遇到此问题的任何人,我错误地从 this.props.params.userId
返回了 id 作为字符串,因此我必须使用 parseInt()
定义它> 像这样:
const userId = parseInt(this.props.params.userId)
最佳答案
您可以简单地使用Array的过滤方法:
render(){
return (
<div>
{
if(this.params.userId) {
const postsForUser = posts.filter(post => post.userId == this.params.userId);
//renderPostList(postsForUser)
} else {
//renderPostList(posts)
}
}
</div>
)
}
关于javascript - 在 React/Redux 中过滤数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40256787/