Answer the question
In order to leave comments, you need to log in
Understanding the React lifecycle coupled with getting data from the server?
Hello. Help me understand how the react lifecycle works.
The code contains the code of the component. At the moment of ComponentDidMount, the data is fetched, gets into the Redux store, from where it successfully gets into the props of the component.
In this example, curPrice is the props received from the server. amount - the props received from the parent component.
Next, I try to "catch" curPrice in the lifecycle methods, but it is displayed as it should.
Further questions go in the course of the code.
class Card extends Component {
state = {
newPrice: null,
};
componentDidMount() {
const { fetchPrice } = this.props;
fetchPrice(fetchType);
}
shouldComponentUpdate(nextProps, nextState) {
console.log(this.props.curPrice); // undefined - почему???? - ведь мы curPrice передали
// в this.props при рендере
console.log(nextProps.curPrice); // {USD: 100} // а здесь они есть))
return true;
}
// Тут я обновляю страницу и смотрю что приходит, или не поможет?...
componentDidUpdate(prevProps, prevState) {
console.log(prevProps.curPrice); // undefined - почему????
}
static getDerivedStateFromProps(props, state) {
console.log(props.amount); // видна с первого рендер
console.log(props.curPrice); // видна сразу со второго render
// Поэтому чтобы записать State - приходится делать дополнительную проверку,
//которую я нигде в примерах не встречал - это правильно?..
if (props.curPrice) {
return { newPrice: props.curPrice };
} else return null;
}
render() {
const { curPrice, amount } = this.props;
return (...);
}
}
const mapStateToProps = (state, ownProps) => {
return {
curPrice: state.prices.types[ownProps.idx],
};
};
const mapDispatchToProps = {
fetchPrice,
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Card);
Answer the question
In order to leave comments, you need to log in
In this example, curPrice is the props received from the server
Therefore, in order to write the State, you have to do an additional check,
which I have not seen anywhere in the examples - is that right? ..
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question