如何过滤和刷新数组对象

时间:2017-11-10 02:59:23

标签: jquery reactjs preact

我想点击按钮时过滤和刷新数组对象。这是我的代码:

file_line { 'catalina':
  ensure => present,
  path   => '/etc/catalina/startup.sh',
  line   => 'export CATALINA_HOME=\"/home/john/apache-tomcat-6.0.44\"',
  match  => 'export CATALINA_HOME=\"/home/john\"',
}
触发 handleClick (event) { event.preventDefault() var el = event.target if (el.name === 'diploma') { this.setState({activeIndex: true}) this.state.results.filter((el) => el.title.toLowerCase().indexOf('diploma') > -1 ); } else { this.setState({activeIndex: false}) this.state.results.filter((el) => el.title.toLowerCase().indexOf('management') > -1 ); } } fetchAPI(url) { return fetch(url) .then((response) => { if (response.status >= 400) { throw new Error('Bad response from server'); } return response.json(); }); } componentDidMount() { const that = this; const url = 'https://d1zh5hbzybtmpd.cloudfront.net/api/app/category/' + that.props.categoryId; that.fetchAPI(url).then((data) => { that.setState({ result: data.category, results: data.courses.courses }); }); } render({ }, { result={}, results=['', '', '', '', '', '', '', '', '', ''] }) { return ( 操作时,不会刷新

列表。请让我知道如何解决它。感谢。

2 个答案:

答案 0 :(得分:1)

我想你想要过滤一些对象,只需要setState({results:newResults})

 handleClick (event) {
    event.preventDefault()
    var el = event.target

    if (el.name === 'diploma') {
        this.setState({
            activeIndex: true,
            results: this.state.results.filter(el => el.title.toLowerCase().indexOf('diploma') > -1)
        });
    } else {
        this.setState({
            activeIndex: false,
            results: this.state.results.filter((el) => el.title.toLowerCase().indexOf('management') > -1);
        })

    }
}

答案 1 :(得分:0)

您需要设置results的状态才能生效。但是,您的代码在某些情况下也可能有效,但它不一致,并且在回调中改变状态变量通常不是一个好主意。

handleClick (event) {
    event.preventDefault()
    var el = event.target

    if (el.name === 'diploma') {
        const newResults = this.state.results.filter((el) =>
            el.title.toLowerCase().indexOf('diploma') > -1
        );
        this.setState({activeIndex: true, results: newResults});
    } else {
        const newResults = this.state.results.filter((el) =>
            el.title.toLowerCase().indexOf('management') > -1
        );
        this.setState({activeIndex: false, results: newResults});
    }
}