I have been learning React over the past few days, looking at a few tutorials and explanations regarding the different ways in which you can write different elements. However there is one I have been most curious about - the setState function to update/override the state properties of a component.
For example, imagine I have a class with the following:
class Photos extends React.Component { constructor() { super() state = { pictures: [] } } componentDidMount() { // This is where the fetch and setState will occur (see below) } render() { return { <div className="container"> {this.state.pictures} </div> } } } This example sees me fetch images from an API.
Given that I have performed my fetch, map and return for this function - I will then update the pictures: [] state array with the results gained in the API call.
My question stems from the differing methods I have seen regarding how to update/override the pictures state property.
I have seen it written in 2 varying ways:
1) This seems to be a very simple and easy to read method
this.setState({pictures: pics})
2) This is more complex but I have see it described as a more safe method
this.setState(prevState => ({ pictures: prevState.pictures.concat(pics) })) Could somebody please explain the merits of using either? I want to be consistent with code in the future, dealing with props and states etc, so the most versatile method would of course be preferred.
state.picturestopics, whereas version 2 setsstate.picturesto the previousstate.pictureswithpicsappended to the end.