反应数组中的更改状态(用于循环) [英] React change state in array (for loop)

查看:98
本文介绍了反应数组中的更改状态(用于循环)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有航班的州,我有一个滑块可以更改最高价格,以更改航班元素的可见性.

I have a State with flights, and I have a slider to change the max price to change visibility of the flight elements.

maxpriceFilter() {

    var flightOffer = this.state.flightOffer;
    var sliderPrice = this.state.sliderPrice;

    for (var i = 0; i < flightOffer.length; i++) {
        if( flightOffer[i].price > sliderPrice) {   

            this.setState(
                {[flightOffer[i].hiddenprice] : true}
            );
        };
    }

这段代码在状态的根中添加了一个状态为true的未定义字段.但是我也无法使计算字段工作..

This code is adding a undefined field with status true in the root of the state though.. I cant find any best practice on this, other then using computed fields. But I cant get the computed field working either..

有人可以在这里帮我吗?

Could someone please help me out here?

推荐答案

您不想在循环中进行setState调用,因为它将使react组件多次渲染.建立一个新的状态对象,并调用一次setState.您也不想通过if语句将其过滤掉,而是将以前的值设置为hidden:

You don't want to do a setState call in a loop, that will have the react component render multiple times. Build a new state object and call the setState once. You also don't want to filter it out by an if statement, but set previous values to hidden:

maxpriceFilter() {

    var flightOffer = this.state.flightOffer;
    var sliderPrice = this.state.sliderPrice;
    var newState = {};

    for (var i = 0; i < flightOffer.length; i++) {
        newState[flightOffer[i].hiddenprice] = flightOffer[i].price > sliderPrice;
    }

    this.setState(newState);

    // ...
}

如果您仍然遇到问题,则可能是hiddenprice属性不是您所期望的?可能还需要发布render()函数.

If you're still having issues, it could be that the hiddenprice property isn't what you expect? Might need to post your render() function as well.

这篇关于反应数组中的更改状态(用于循环)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆