A
A
AleDv2020-04-21 18:22:19
React
AleDv, 2020-04-21 18:22:19

How to catch props change in react?

I'm learning react. One screencast advises to catch props changes in the componentWillReceiveProps hook, however it is now deprecated and recommends using the getDerivedStateFromProps static method, which should change the state.

However, the method is called, the condition is triggered, but the state does not change.

static getDerivedStateFromProps(props, state) {
        if (props.isOpened !== state.isOpened) {
            return {
                isOpened: props.isOpened
            };
        }

        return null;
    }


What am I doing wrong?

UPD. Full Component Class

import React, { Component } from 'react';
import './style.sass';

class Article extends Component {
    constructor(props) {
        super(props);

        this.state = {
            isOpened: props.isOpened,
        };

        this.article = props.article;
    }

    // componentWillReceiveProps(nextProps) {
    //     console.log(nextProps.isOpened, this.props.isOpened);
    //
    //     if (nextProps.isOpened !== this.props.isOpened) {
    //         this.setState({
    //             isOpened: nextProps.isOpened
    //         });
    //     }
    // }

    static getDerivedStateFromProps(props, state) {
        if (props.isOpened !== state.isOpened) {
            console.log('getDerivedStateFromProps', props.isOpened, state);

            return {
                isOpened: props.isOpened
            };
        }

        return null;
    }

    handleClick = () => {
        this.setState({
            isOpened: ! this.state.isOpened,
        });
    };

    getDescription = () => {
        return (
            <p>{ this.props.article.description }</p>
        )
    };

    render() {
        return (
            <div className='card article'>
                <div className='card-header'>
                    <h6>{ this.props.article.title }</h6>
                    <button onClick={this.handleClick}
                            className='btn btn-primary btn-sm float-right'>
                        { this.state.isOpened ? 'Закрыть' : 'Открыть' }
                    </button>
                </div>

                <div className='card-body'>
                    { this.state.isOpened ? this.getDescription() : '' }
                </div>
            </div>
        );
    }
}

export default Article;


UPD . Link to sandbox . It is necessary that when reversing the list of articles, the description of the first article is always open.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Klimenko, 2020-04-21
@yeswell

You are stating props when you can just use props

T
tervizator, 2020-04-21
@tervizator

If you are in a class component, then use setState() to change local data, it is in the React documentation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question