A
A
Adventure20682018-10-17 12:50:28
React
Adventure2068, 2018-10-17 12:50:28

How to update state when updating props?

There is a component that receives a prop from the parent component, which changes depending on the value of the input in the parent. component. Depending on this prop, you need to filter the data array, and assign it to the state of this component. What is the best way to do this? If I update the state in componentDidUpdate it throws an infinite loop error.

class CardsWrapper extends Component {
    constructor(props){
        super(props)
        this.state = {
            films: [],
            currentSearch: props.currentSearch
        }

    }

    componentDidUpdate(prevProps, prevState){
        let search = this.props.currentSearch
        let films = filmsArray.filter(obj => !obj.title.search(search))

        }
    }

    render(){
        return (
            <div>
                <ul>
                    {this.state.currentSearch   }
                </ul>
            </div>
        )
    }


}

export default CardsWrapper

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2018-10-17
@Adventure2068

If I update the state in componentDidUpdate it throws an infinite loop error.

Add a check that props have changed:
componentDidUpdate(prevProps, prevState) {
  if (this.props.currentSearch !== prevProps.currentSearch) {
    // ваш код с вызовом setState
  }
}

J
Jasulan98, 2018-10-17
@Jasulan98

First, you need to check whether to update or not (true or false) through shouldcomponentupdate.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question