Reputation: 10896
In React js component I have this code
this.state.author[field] = value;
In the console I got a warning: Do not mutate state directly. Use setState()
How could I put author with [] in setState?
Upvotes: 0
Views: 616
Reputation: 448
**
React uses setState function to update the state of component, you can do somethings like below
**
let newAuthor = [...this.state.author];
newAuthor[field] = value;
this.setState({author:newAuthor});
Upvotes: 1
Reputation: 214957
If field is a variable that holds the key, you can do this:
this.setState({author: {...this.state.author, [field]: value}})
Upvotes: 2