React setState + Where does 'prevState' come from?

前端 未结 2 982
孤独总比滥情好
孤独总比滥情好 2021-02-02 05:47

I just started learning React and JavaScript.
While going through the tutorial, I got to this example code of a component, which creates a toggle button.
This is part of

2条回答
  •  感动是毒
    2021-02-02 06:42

    1. prevState is provided by React along with props, both of which are optional.

      • Update 04/13/19: React has changed the setState function documentation by renaming prevState to updater. The callback function still takes two arguments; the state and props at the time the change is being applied.
    2. The parenthesis allow multiple lines where if you didn't use the parenthesis you'd be forced to used a return. You could use a single line but you don't need the curly braces.

      • Update: I forgot to mention a specific case where it is required to have parenthesis. If you're returning an object without a return statement you must wrap it in parenthesis. Thank you @joedotnot for catching that. So () => {foo: true} will throw an error because it looks like a function and foo: true is an invalid line. To fix this it must look like () => ({ foo: true })

提交回复
热议问题