javascript 如何在 ReactJS 中过滤数据集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30682881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:31:33  来源:igfitidea点击:

How to Filter data collection in ReactJS

javascriptreactjs

提问by agaezcode

I'm new to ReactJS and I'm trying to figure out how it works.

我是 ReactJS 的新手,我正试图弄清楚它是如何工作的。

I was playing with it a little in JsBin and I have successfully created some components to fetch data from an api... but, I felt a little confused when I've tried implement the code to filter that collection.

我在 JsBin 中玩了一点,我已经成功创建了一些组件来从 api 获取数据......但是,当我尝试实现代码来过滤该集合时,我感到有些困惑。

Here is the JsBin linkthat I was trying to implement the filter feature.

这是我试图实现过滤器功能的JsBin 链接

Could you help me to understand why it's not working? Thank you.

你能帮我理解为什么它不起作用吗?谢谢你。

采纳答案by Phi Nguyen

In the ContentListcomponent, it should use this.props.filterTextwhich will take the value of the input and compare to your data. When the input value is changed, React will re-render the component which contains this.state.filterText. You can use mapor filtermethod to filter it. Here is an example :

ContentList组件中,它应该使用this.props.filterTextwhich 将获取输入的值并与您的数据进行比较。当输入值改变时,React 会重新渲染包含this.state.filterText. 您可以使用mapfilter方法对其进行过滤。这是一个例子:

var ContentList = React.createClass({

    render: function() {
        var commentNodes = this.props.data.map(function(content) {
                 if(content.description === this.props.filterText){ <-- this makes the filter work !
                    return <ItemRow title={content.owner.login} body={content.description} slug={content.owner.avatar_url}></ItemRow>}
            })
        return (
            <div className='contentList'>
                {commentNodes}
            </div>
        )
    }
})