Hello guys, I'm learning React.
Hello guys, I'm learning React. Everyone is saying *don't change the state directly* instead clone the existing state, add changes to that and then use setState to make changes. But the *state gets changed directly If I make changes to a nested property of the cloned object.* I know cloning makes a shallow copy up to only one level but how do I achieve immutability? I can't get my head around this! Can you tell me how do you tackle this problem?
No any search results
You already invited:
3 Answers
binkley
Upvotes from:
Marion
Upvotes from:
console.log(deepClonedPost === posts); // false
deepClonedPost.post.title = "Updated Post";
deepClonedPost.post.body.p = "Updated Body";
console.log("deepClonedPost", deepClonedPost);
console.log("Post", posts);
console.log("Post Body", posts.post.body.p); // just body
console.log("deepClonedPost Body", deepClonedPost.post.body.p); //updated body
Guilbaud
Upvotes from:
const newPost = {…posts.post,
title: 'Updated post',
body: {
...posts.post.body,
p: 'new Body',
}
};