简体   繁体   中英

React, change state works only for one function

I have a problem with my react app. I have form with 2 components (two separate pickers), and I need to change component state when the date is incorrect. Here is the code:

    constructor(props: EditFormProps) {
    super(props);

    this.state = {
        isValidDate: true,
        isValidTime: true
    } as EditFormState;

    this.validateDate = this.validateDate.bind(this);
    this.validateTime = this.validateTime.bind(this);
}

render() {
       return (
           <div>
                <FormSection title={FLIGHT_DATES} className="flight-dates">
                    <div>
                        <DateRange validateDate={this.validateDate} />
                    </div>
                    <div>
                        <TimeOfDate validateTime={this.validateTime} />
                    </div>
                </FormSection>
            </div>
        );
    }
}


private validateDate(isValidDate: boolean) {
    this.setState({
        ...this.state,
        isValidDate: isValidDate,
    } as EditFormState);
}

private validateTime(isValidTime: boolean) {
    this.setState({
        ...this.state,
        isValidTime: isValidTime,
    } as EditFormState);
}

When I have only one function like validateDate its set state for isValidDate without problem, but when i have 2 functions (validateDate and validateTime) i got proper parameter for validateDate but state is always the same (it's working fine for isValidTime). When I change positions in FormSection and TimeOfDate is 1st I have same problem for isValidTime state and isValidDate it woks good. So probably I have some bigger problem in my project, but maybe there is other way to set this state or pass parameter from DateRange or TimeOfDay?

I think that the problem with your code is that you are reading from this.state inside the this.setState() call.

In this case this.state is not guaranteed to contain the up-to-date state.

You should pass a function to this.setState() rather than an object. Eg:

private validateDate(isValidDate: boolean) {
  this.setState((prevState, props) => ({
    ...prevState,
    isValidDate: isValidDate
  })
}

More info in the react docs .

Please, try to remove ...this.state from the validation functions

Maybe you call both validation function in the same time-frame? React merges multiple setState functions into one, so it is possible that you have something like this:

set newIsValidDate => set newIsValidTime and setOldIsValidTime

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM