Skip to content

confusion about setState on page 411 of the book #99

@pennsong

Description

@pennsong

in the api doc: https://reactjs.org/docs/react-component.html#setstate

state is a reference to the component state at the time the change is being applied. It should not be directly mutated. Instead, changes should be represented by building a new object based on the input from state and props. For instance, suppose we wanted to increment a value in state by props.step:
this.setState((state, props) => {
return {counter: state.counter + props.step};
});

in the book "pro-react-16" page 411:

toggleProMode = () => {
this.setState(state => state.proContextData.proMode
= !state.proContextData.proMode);
}

according to the api doc, page 411 is not workable, because in the function

state => state.proContextData.proMode = !state.proContextData.proMode

there is no explicit return, so the return value is the result of 'state.proContextData.proMode = !state.proContextData.proMode', which is !state.proContextData.proMode, let's assume it's 'true', obviously 'true' is not the state object
but I tested the code, it works, could you please explain why? thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions