React change state in array (for loop)

一世执手 提交于 2019-12-11 11:32:39

问题


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}
            );
        };
    }

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?


回答1:


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);

    // ...
}

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.




回答2:


Instead of doing your looping when you're updating the state, why not just do the switch on render?

You're probably already looping over all flightOffers in render(). So, just add the check there. Inside your render, pass hiddenPrice={offer.price > sliderPrice} as a prop, or use it directly where you control the visibility.

Why? Because the visibility of a specific item in this case is not state. It is a result of the state.



来源:https://stackoverflow.com/questions/37657635/react-change-state-in-array-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!