Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJoseph Butterfield
Full Stack JavaScript Techdegree Graduate 16,430 PointsHow does prevState reference this.state before change?
I think I have analyzed this correctly, but I want to be sure...
So once Guil changes the function from a direct reference to the Class state, TO a callback function, how is the parameter passed into the callback function referencing the class's initial state without "this.state.score"? prevState just seems an arbitrary parameter, but how does it reference the previous state (NOT this.state)?
--Method references Class state directly
incrementScore = () => { this.setState({ score: prevState.score + 1 }); } --> this.setState( {/* Object with updated state */ } )
--Method uses callback function to reference previous state
incrementScore = () => { this.setState( prevState => ({ score: prevState.score + 1 })); }
https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous React Docs specify a callback function, in which two parameters are passed to reference the props and previous state as follows:
this.setState( (state, props) => { stateName: state.stateName + 1 } )
So are we saying that we can simply omit the extended React setState() param "props" and use the arbitrary prevState as the "state" param? If so, does React default a single parameter to the "state" parameter, and we have to declare (state, props) to actually read the "props" parameter, if we choose to do so? Example:
this.setState( state => { score: state.score + 1 } )
This is the only sensible thing to me similar to last unit's Express .get() and .use() callbacks which contain the (res, req, next) parameters, regardless of whether res.method(), req.method(), "next" param, or even "err" param are actually used within the callback.
1 Answer
Sean Paulson
6,669 PointsYes in JS if you have a CB function that takes cb(param1, param2, param3) you can just pass cb(p1, p2) Unless of course its a required param. usually it will say in the docs if it is required. What you cant do is skip a param cb(p1, p3).