简体   繁体   中英

Why is this counted as mutating state?

handleClick(event) {
let value = event.target.value;

this.setState({ question: (this.state.question += value) });

I get a warning:

Do not mutate state directly. Use setState() react/no-direct-mutation-state

if I try to load the page with this code.
How can I fix it so it doesn't give me this warning?
It says to use this.setState , but that's what I'm doing.

You're doing an unnecessary assignment addition to this.state.question - you only need addition here. Furthermore, when updating state based on a previous value, the docs state :

React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

The proper way to update state based on a previous value is to pass in an update function that works off the previous value, ie:

this.setState(prevState => ({ question: prevState.question + value }));

The mistake is here :

this.state.question += value

+= is the operator used to add right operand to the left operand. You are trying to add value to this.state.question.

The correct way to do it is :

this.setState(previousState => ({ question: previousState.question + value }));

This is considered mutating state because you are assigning a value to this.state.question in the expression (this.state.question += value) . I have pasted a link to a Code Sandbox you can view to see how to correctly implement this behavior.

Code Sandbox

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