Answer the question
In order to leave comments, you need to log in
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;
}
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;
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question